1

In a shell script, I get the certain number of a line in a file and store it in a variable using the code below:

res=$(grep -n '123' somefile.txt | sed 's/^\([0-9]\+\):.*$/\1/')

Now I want to write in 3 lines after this line, so I used these codes :

sed -i '$res\anything' somefile.txt
sed -i '$resianything' somefile.txt

but they don't work. It seems that sed doesn't accept variables. How can I solve it? Is there any alternative way?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
pouya
  • 51
  • 1
  • 7

2 Answers2

1

Some tips before pointing out the duplication:

  • Variables won't be expanded within single quotes.
  • Variable name boundaries are not detected automatically. $resianything will not expand to the value of the variable res followed by the string ianything, but rather to the value of the variable with the name resianything, which presumably is empty. You can detect this kind of error by adding set -o nounset (and ideally -o errexit) at the top of your script.
  • You'll definitely want to escape the string you're inserting back into a sed command.
l0b0
  • 55,365
  • 30
  • 138
  • 223
1

You seem to be asking why the $res isn't expanding. That isn't a sed issue; it's the shell. Typically bash &c. don't expand variables within single quotes. Try double quoting that bit.

Also, one method for separating your variable from following alphanumeric text is to use curly braces. Try ${res}anything instead of $resanything, for example.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
D Hydar
  • 502
  • 2
  • 8
  • hi, thanks. i used >> sed -i ${res}ianything somefile.txt and it worked. without i, at the end of ${res}i it didn't write the "a" at the first of anything – pouya Jun 28 '16 at 06:13