Anonymous Anonymous - 1 year ago 168
Bash Question

How to use 'sed' in shell script to replace a line in a file

I've a file with a line contains special characters like % ^ #$ @#$. I tried to use sed tool to replace this line with pattern like this (name=value where value contains special characters).

sed -i 's|abc.defef.efefef.gege=%6p [%d{HH:mm:ss}] %c{1}@%L: %m%n|abc.defef.efefef.gege=%7p [%d{HH:mm:ss}] %d{1}@%X|g' FILE_NAME

How can I do this?



%6p [%d{HH:mm:ss}] %c{1}@%L: %m%n

Need to replace value with new value:
%7p [%d{HH:mm:ss}] %d{1}@%X

Answer Source

You forgot to escape the special characters in the expression.

I've made a couple of changes:

  • Escaped ., otherways it will match any characters.
  • Added ^ so the key starts at the beginning of the line (otherwise you can match a postfix of another key).
  • Removed the search for the original value (I assume it doesn't matter what it was), so you don't have to escape all the special characters there.
  • Replaced the key in the replace part with \1 to avoid duplication in the code.

sed 's|^\(abc\.defef\.efefef\.gege=\).*|\1%7p [%d{HH:mm:ss}] %d{1}@%X|g'