Ubuntu – Using a variable inside `sed` command

command linescripts

I am using this command to copy certain line from one file to another.Its working fine.No issue with it.

sed -f <(sed -e '1,10d; 12,$d; x; s/.*/10a\/;p; x' ../log/file2.txt ) ../log/file4.txt > ../log/file5.txt

The problem is instead of 10, I want to use variable VAR1 (where var1=10). The $VAR1 is not working.

I tried this command:

sed -f <(sed -e '1,$VAR1d; 12,$d; x; s/.*/10a\/;p; x' ../log/file2.txt ) ../log/file4.txt > ../log/file5.txt

Please help me.

Best Answer

The shell doesn't expand variables inside single quotes. You need to use double quotes. Also, as Danatela says, you also need curly brackets in this case. Since the shell will then attempt to expand the $d too, you need to escape the $.

sed -f <(sed -e "1,${VAR1}d; 12,\$d; x; s/.*/10a\/;p; x" ../log/file2.txt ) ../log/file4.txt > ../log/file5.txt

I'm not sure if there are other parts in the quotes that will also need escaping since you use double quotes now (e.g. *?), so you can always switch between double and single quotes instead, using the former only when necessary.

sed -f <(sed -e '1,'"${VAR1}"'d; 12,$d; x; s/.*/10a\/;p; x' ../log/file2.txt ) ../log/file4.txt > ../log/file5.txt
Related Question