sed insert variable before last line

I would like to insert a variable before the last line.

This is my file.

$ cat file.txt
one
two
three
four
five

When I try without using variables, it works fine.

$ sed -i '$i name' file.txt
$ cat file.txt
one
two
three
four
name
five

When I use a variable, it doesn't work. I tried different combinations of double quotes and backslashes.

$ NAME=name
$ sed -i '$i "$NAME"' file.txt
$ cat file.txt
one
two
three
four
"$NAME"
five
0

2 Answers

In bash, single-quotes are for fixed, literal strings. Double quotes are used where you want variable interpolation, command substitution, etc to occur.

Your sed command needs to use both a literal $ (so that the i command applies to the last line of the file) AND $NAME for the variable to interpolate. To do this, you need to "escape" the literal $ with a backslash so that the shell doesn't interpret the $i in your sed script as "replace with the contents of variable $i" instead of "literal $ followed by literal i":

BTW, it's better to test things like this without using the -i option, so that sed doesn't mess up your input file while you're figuring out the correct syntax. Add the -i later when you're sure it's doing exactly what you want.

$ NAME=name
$ sed "\$i $NAME" file.list
one
two
three
four
name
five

Another way:

$ NAME=name
$ sed '$i '"$NAME" file.list
one
two
three
four
name
five

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like