On 1/2/22 6:20 PM, The Wanderer wrote:
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"?

"Globally" just means I want to replace the first instance, rather than appending the 'g' modifier to the sed expression.


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.

This works, as I mentioned in another reply. The context here is a file which would have something like: ';extension=gd', to be replaced by 'extension=gd'. That is, I want to programmatically uncomment a line, in most cases.

Paul

Reply via email to