8

I have a file called ethernet containing multiple lines. I have saved one of these lines as a variable called old_line. The contents of this variable looks like this:

SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="2r:11:89:89:9g:ah", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"

I have created a second variable called new_line that is similar to old_line but with some modifications in the text.

I want to substitute the contents of old_line with the contents of new_line using sed. So far I have the following, but it doesn't work:

sed -i "s/${old_line}/${new_line}/g" ethernet
anubhava
  • 761,203
  • 64
  • 569
  • 643
user2835098
  • 155
  • 1
  • 1
  • 10

2 Answers2

12

You need to escape your oldline so that it contains no regex special characters, luckily this can be done with sed.

old_line=$(echo "${old_line}" | sed -e 's/[]$.*[\^]/\\&/g' )
sed -i -e "s/${old_line}/${new_line}/g" ethernet
PatJ
  • 5,996
  • 1
  • 31
  • 37
5

Since ${old_line} contains many regex special metacharacters like *, ? etc therefore your sed is failing.

Use this awk command instead that uses no regex:

awk -v old="$old_line" -v new="$new_line" 'p=index($0, old) {
      print substr($0, 1, p-1) new substr($0, p+length(old)) }' ethernet
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thanks, I copied the script but it only echoes the variable contents of the new variable in my terminal. It doesn't modify the file **ethernet**. What am I doing wrong? – user2835098 Feb 17 '15 at 12:30
  • 1
    It's not "wrong" per se, it's just that plain-jane Awk does not support inline editing. If you have Gawk, try adding an `--inline` option. If not, store in a temp file and move it on top of the original. – tripleee Feb 17 '15 at 12:36
  • Ok, in case I use gawk, what should the command look like? If gawk doesn't work, I need to replace the old line, is there a way to delete the line? – user2835098 Feb 17 '15 at 12:41
  • 1
    Same command will work on gawk also (in fact I have also tested it on gawk) – anubhava Feb 17 '15 at 14:09
  • 1
    @tripleee: I think you meant in-_place_ editing and `-i inplace`, available in Gawk v4.1+ – mklement0 Jun 02 '17 at 02:25
  • 1
    Oh, quite so, sorry for the confusion. – tripleee Jun 02 '17 at 03:26