1

I'm trying to insert into a text file the string cd $var at the second line using sed, but it doesn't seem to work. I'm using the syntax for inserting a line at a specific line in a file,

sed -i '2icd $var' FILE

The format of which was found as the response to this question:

Insert a line at specific line number with sed or awk

My best guess is that sed is interpreting the command literally and evaluating it instead of copying it in. However, all of my attempts at forcing it to be evaluated simply as a string have failed. My attempts so far:

sed -i '2i\cd $var' FILE
sed -i '2i\cd \$var' FILE
sed -i "2i'cd $var'" FILE

and

Line='cd $var'
sed -i "2i$Line" FILE

I was fairly sure this last attempt would succeed, due to the hard quotes, but it still failed.

In fact, this also failed,

sed -i '2icd' FILE

Yet this succeeded (Just to confirm the general format):

sed -i '2ic' FILE

Just to be clear, all 5 of the failed attempts yielded the same error: A blank line was inserted at the desired location.

Community
  • 1
  • 1
Borealis126
  • 33
  • 1
  • 5
  • `sed -i '2icd $var' FILE` works fine for me. – Tiago Lopo Jul 21 '14 at 20:31
  • Same here, I have no trouble with that command. I'm using Cygwin on Windows. Maybe $var is evaluating to some unexpected defined variable. On my system, being windows, there is no such variable syntax to conflict with existing variables. I'd do an ECHO MyVar=$var and see what you get. But that should still yield the 'cd ' part of it. Mysterious – jxramos Jul 21 '14 at 20:34
  • Thanks for the responses- I've verified that the syntax sed -i '2icd $var' FILE DOES work, just not inside the program I was running. So something else was going on. I ended up taking a different direction with that project, but if I end up being able to isolate what exactly was wrong, I'll keep this post updated. – Borealis126 Jul 22 '14 at 14:31

1 Answers1

2
sed -i "2 i\\
$var" file

need a escape NewLine normaly after the i and depending the OS/sed a space before and/or after the i also. Finaly, with double quote, escape the \

NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43