5

I found interesting discussion here and tried the solution given with sed

How to insert a text at the beginning of a file?

https://stackoverflow.com/a/9533736/13353532

It works with normal text, but not when the text is saved in a variable.

wolf@linux:~$ cat file.txt 
1
2
3
wolf@linux:~$ 

Add text (<added text>) to the beginning of the file

wolf@linux:~$ sed -i '1s/^/<added text>\n/' file.txt
wolf@linux:~$ 

It works!

wolf@linux:~$ cat file.txt 
<added text>
1
2
3
wolf@linux:~$ 

However, when I tried it with variable it doesn't work anymore.

wolf@linux:~$ var='Text 1'
wolf@linux:~$ echo $var
Text 1
wolf@linux:~$ 

wolf@linux:~$ cat file.txt 
1
2
3
wolf@linux:~$ sed -i '1s/^/"$var"\n/' file.txt
wolf@linux:~$ cat file.txt 
"$var"
1
2
3
wolf@linux:~$ 

Instead of "$var", how do I call the actual value of $var in sed command? I use GNU sed 4.7:

sed (GNU sed) 4.7 Packaged by Debian
Copyright (C) 2018 Free Software Foundation, Inc.
0

1 Answer 1

9

The problem is that you have - as is recommended - enclosed the sed instructions in single quotes ' ... '. However, inside single quotes, variable expansion such as $var is disabled, and the expression remains verbatim.

As a solution, you can enclose the instructions in double quotes:

sed -i "1s/^/$var\n/" file.txt

Note however that I would recommend using the "insert" command for this purpose:

sed -i "1i $var" file.txt

will insert the content of $var before line 1.

Edit

As correctly stated by @DigitalTrauma in a comment: if you want to guard "all but the variable" against (unwanted) expansion, you can use a concatenated string argument with mixed quoting, which however mainly makes sense in the s command example:

sed -i 's/^/'"$var"'\n/' file.txt
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .