How to remove only the first occurrence of a line in a file using sed
bash, linux, sed, shell
Solution
You could make use of two-address form:
sed '0,/tat/{/tat/d;}' inputfile
This would delete the first occurrence of the pattern.
Quoting from `info sed`:
A line number of `0' can be used in an address specification like
`0,/REGEXP/' so that `sed' will try to match REGEXP in the first
input line too. In other words, `0,/REGEXP/' is similar to
`1,/REGEXP/', except that if ADDR2 matches the very first line of
input the `0,/REGEXP/' form will consider it to end the range,
whereas the `1,/REGEXP/' form will match the beginning of its
range and hence make the range span up to the _second_ occurrence
of the regular expression.
Problem
I have the following file ``` titi tata toto tata ``` If I execute ``` sed -i "/tat/d" file.txt ``` It will remove all the lines containing `tat`. The command returns: ``` titi toto ``` but I want to remove only the first line that occurs in the file containing `tat`: ``` titi toto tata ``` How can I do that?