Replace string variable with string variable using Sed

43,070

Solution 1

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

Solution 2

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
Share:
43,070
user2835098
Author by

user2835098

Updated on July 09, 2022

Comments

  • user2835098
    user2835098 almost 2 years

    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
    
  • user2835098
    user2835098 about 9 years
    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?
  • tripleee
    tripleee about 9 years
    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.
  • user2835098
    user2835098 about 9 years
    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?
  • anubhava
    anubhava about 9 years
    Same command will work on gawk also (in fact I have also tested it on gawk)
  • user2835098
    user2835098 about 9 years
    Yes, that totally did the trick! I am very grateful PatJ!!
  • PatJ
    PatJ about 9 years
    For a more general case, "/" should be escaped too as long as "\" and "&" in the new_line variable.
  • mklement0
    mklement0 almost 7 years
    @tripleee: I think you meant in-place editing and -i inplace, available in Gawk v4.1+
  • tripleee
    tripleee almost 7 years
    Oh, quite so, sorry for the confusion.