简体   繁体   中英

Replace line in text containing special characters (mathematical equation) linux text

I want to replace a line, that represents a part of mathematical equation:

f(x,z,time,temp)=-(2.0)/(exp(128*((x-2.5*time)*(x-2.5*time)+(z-0.2)*(z-0.2))))+(  

with a new one similar to the above. Both new and old lines are saved in bash variables.

Main problem is that mathematical equation is full with special characters that do not allow proper search and replace in bash mode, even when I used as delimiter special character that is not used in equation.

I used

sed -n "s|$OLD|$NEW|g" restart.k

and

sed -i "s|$OLD|$NEW|g" restart.k

but all times I get wrong results. Any idea to solve this?

There is only * in your pattern here that is special for sed , so escape it and do replacement as usual:

sed "s:$(sed 's:[*]:\\&:g' <<<"$old"):$new:" infile

if there are more special characters in your real sample, then you will need to add them inside bracket [] ; there are some exceptions like:

  • if ^ character: it can be place anywhere in [] but not first character, because ^ character at first negates the characters within its bracket expression.
  • if ] character: it should be the first character, because this character is also used to end the bracket expression.
  • if - character: it should be the first or last character, because this character is also can be used for defining the range of characters too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM