pass a variable line number to sed

num=10
sed -n '$num p' test.txt

sed -n '10 p' test.txt works

however i am putting the sed command in a loop and the line number is not static
Can someone please help me how to achive this.

Variables do not expand inside single quotes. Use double quotes.

> VAR=asdf
> echo '$VAR'

$VAR

> echo "$VAR"

asdf

>

However, I am concerned about your use of sed here. Are you running sed 100 times to read 100 lines?? That's like making 100 phone calls to say 100 words. It'd be much better to use read in a while loop:

while read LINE
do
        echo "Got $LINE"
done < inputfile

read can even do input splitting, on spaces by default or other things controlled by the special IFS variable, which makes a lot of processing much simpler.

1 Like