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

Re: Replace line in file based on pattern



On Sun, Jan 02, 2022 at 06:20:15PM -0500, The Wanderer wrote:
> If you mean that you want to only replace the first matching line in the
> file, but leave any subsequent matching lines alone... I've never
> actually had occasion to do that, but a bit of Googling (for 'sed first
> match only') found me
> 
> https://stackoverflow.com/questions/148451/how-to-use-sed-to-replace-only-the-first-occurrence-in-a-file
> 
> which looks like at least the seed of a way to do it; see also below.

Why does everyone think sed is an appropriate tool for this?  It's
some sort of malevolent meme, I swear.

unicorn:~$ printf %s\\n foo foo foo | awk '!done && /foo/{$0="bar"; done=1} 1'
bar
foo
foo

Of course, given the ORIGINAL question, the best tool is neither of these.
It's something like ansible or puppet.  Or if you insist on jury-rigging
crap together with stone knives and bearskins, ssh and patch.

See also <http://backreference.org/2011/01/29/in-place-editing-of-files/>.


Reply to: