Saturday, July 10, 2010

Replace entire line that contains given text

I need to replace an entire line that contains a certain string with another line. This is especially useful in case of editing configuration files that have predefined fields but values may be different.


Say the string you are looking for is STRING_TO_BE_REPLACED.
And the line you want to insert is LINE_TO_REPLACE_WITH.
 

sed 's/^.*STRING_TO_BE_REPLACED.*$/LINE_TO_REPLACE_WITH/'  input_file > new_file

The ^ is a start of line anchor, the '.*' is a wildcard, the $ is a end of line anchor.