Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string variable with string variable using Sed [duplicate]

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
like image 243
user2835098 Avatar asked Feb 17 '15 11:02

user2835098


Video Answer


2 Answers

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
like image 65
PatJ Avatar answered Oct 20 '22 18:10

PatJ


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
like image 5
anubhava Avatar answered Oct 20 '22 18:10

anubhava