9

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
2
  • Try without the {} around variables ? Also check stackoverflow.com/questions/8938571/… Commented Feb 17, 2015 at 11:09
  • Thanks, but unfortunately this doesn't work either. Commented Feb 17, 2015 at 11:29

2 Answers 2

13

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
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, that totally did the trick! I am very grateful PatJ!!
For a more general case, "/" should be escaped too as long as "\" and "&" in the new_line variable.
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

6 Comments

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?
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.
Same command will work on gawk also (in fact I have also tested it on gawk)
@tripleee: I think you meant in-place editing and -i inplace, available in Gawk v4.1+
Oh, quite so, sorry for the confusion.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.