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

Re: Replace line in file based on pattern



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

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

but I personally prefer to give exact matches.

Cheers,
Andy

-- 
https://bitfolk.com/ -- No-nonsense VPS hosting


Reply to: