Home > Back-end >  Read specific line of a file and then set it as a variable
Read specific line of a file and then set it as a variable

Time:07-20

How do I print a specific line of a file new.sh (line 60 in this case) and then set what is printed as a variable?

I want to make sure the new info will be printed in the correct section of the file before executing.

cat -n new.sh | sed -n '60p'

?????? ??????

if [ "$DATA" ]; then
    if [[ "$DATA" == "<data>" ]]; then
        sed -i '60i < new data will be added here. >' new.sh;
    elif [ $DATA != '<data>' ]; then
        echo "Error"
    else
        return 0
    fi
fi

CodePudding user response:

You could do:

data=$(sed -n 60p new.sh)

but if the goal is just to insert the line before line 60 only if line 60 is the string <data>, it seems easier to just put that logic in sed:

sed '60 { /^<data>$/i\
<new data>
}' new.sh

Doing this doesn't give you the error message that you had before, so perhaps you want something like:

if ! awk '60 == NR && /^<data>$/{ print "<new data>"; ok = 1} 1 END{exit !ok}' new.sh; then
    echo Error >&2
fi

CodePudding user response:

LINE=`sed -n 60p <new.sh'
echo "$LINE"
if [ "$LINE" = "<data>" ]
then
    sed -n 1,59p <new.sh
    echo "some new data"
    sed -n 61,$p <new.sh
fi > output.sh
  • Related