[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Replace line in file based on pattern



On 1/2/22 6:18 PM, Andy Smith wrote:
Hello,

On Sun, Jan 02, 2022 at 05:52:36PM -0500, Paul M. Foster wrote:
In a script, I'd like to search for a pattern in a file, and replace that
line entirely with a new line, once (not globally). I've tried

sed -i s/search/new_line/

but this only replaces the string itself. I want the script to find the line
my search term is on, and replace the whole line with my replacement line.

Match the whole line, not just the string.

sed -i 's/^.*search.*$/new line/' filename

This works. I'm not that familiar with regexps, so this didn't occur to me in the first place.


The ^ and $ anchor at start and end respectively and the .* matches
everything.

You can instead use sed's 'c' modifier to tell it to replace the
whole line:

sed -i '/search/new line/c' filename

This did not work, at least the way you've written it here. I can't say why, but it did not make any changes to the file in question.

Paul




Reply to: