How to change the first occurrence of a line containing a pattern?

This might work for you (GNU sed):

sed '1!b;:a;/something/!{n;ba};cCOMPLETE NEW LINE' file

Set up a loop that will only operate from the first line.

Within in the loop, if the key word is not found in the current line, print the current line, fetch the next and repeat until the end of the file or a match is found.

When a match is found, change the contents of the current line to the required result.

N.B. The c command terminates any further processing of sed commands in the same way the d command does.

If there are lines in the input following the key word match, the negation of address at the start of the sed cycle will capture these lines and result in their printing and no further processing.

An alternative:

sed 'x;/./{x;b};x;/something/h;//cCOMPLETE NEW LINE' file

Or (specific to GNU and bash):

sed $'0,/something/{//cCOMPLETE NEW LINE\n}' file

The c\ command deletes all lines between and inclusive the first matching address through the second matching address, when used with 2 addresses, and prints out the text specified following the c\ upon matching the second address. If there is no line matching the second address in the input, it just deletes all lines (inclusively) between the first matching address through the last line. Since you want to replace one line only, you shouldn't use the c\ command on an address range. The c\ is immediately followed by a new-line character in normal usage. The 0,/regexp/ address range is a GNU sed extension, which will try to match regexp in the first input line too, which is different from 1,/regexp/ in that aspect. So, the correct command in GNU sed could be

sed '0,/something/{/something/c\
COMPLETE NEW LINE
}' < in.txt

or simplified as pointed out by Sundeep

sed '0,/something/{//c\
COMPLETE NEW LINE
}' < in.txt

or a one-liner,

sed -e '0,/something/{//cCOMPLETE NEW LINE' -e '}' < in.txt

if a literal new-line character is not desirable.

This one-liner also works as pointed out by potong:

sed '0,/something/!b;//cCOMPLETE NEW LINE' in.txt

Just use awk:

$ awk '!done && sub(/something/,"other-thing"){done=1} {print}' file
one two three
four other-thing
five six
something seven

$ awk '!done && sub(/.*something.*/,"other-thing"){done=1} {print}' file
one two three
other-thing
five six
something seven

$ awk '!done && /something/{$0="other-thing"; done=1} {print}' file
one two three
other-thing
five six
something seven

and look what you can trivially do if you want to replace the Nth occurrence of something:

$ awk -v n=1 '/something/ && (++cnt == n){$0="other-thing"} {print}' file
one two three
other-thing
five six
something seven

$ awk -v n=2 '/something/ && (++cnt == n){$0="other-thing"} {print}' file
one two three
four something
five six
other-thing

Tags:

Sed