On 2022-01-02 at 17:52, Paul M. Foster wrote:
Folks:
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
What do you mean by "globally"?
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.
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.
Anyone know how to do this?
Without re-testing at the moment, I'd say from past experience that you
want:
sed -i 's/^.*search.*$/new_line/'
This matches the beginning of the line, followed by zero or more
characters, followed by the search string, followed by zero or more
characters, followed by the end of the line.