I'm having some trouble with sed and seeing a variable providing a number instruction for an insertion of text at a specific line.

here is the working code without the variable:

sed -i '1i\NewLineHere\' ~/file/location/here.txt

I need to change the number 1 to $var, but with the letter 'i' remaining next to it (no space), while not being seen as part of the variable. I use " " instead of ' ' so that sed can see the variables correctly, I have tried countless different attempts and none have worked. An example of what the problem looks like without any attempt to disconnect the 'i' from the variable while keeping it next to it:

 sed -i "$vari\NewLineHere\" ~/file/location/here.txt

Thanks in advance for any suggestions or answers

1 Answer 1


This is where {} quoting of variable names is useful. In your case, ${var}

For example:

$ var=100
$ echo $vari

$ echo ${var}i

The {...} act as a "scoping" for the variable name.

(Side note: be careful with the \ character when switching between ' and ").

  • brilliant, that nicely separates the variable name, but your warning is also true, as i am experiencing problems with \ while using " how can I avoid this problem?
    – Giles
    Sep 21, 2016 at 23:21
  • 1
    You have to quote them with an additional backslash: echo '\' vs echo "\\" Sep 21, 2016 at 23:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.