This sed
code deletes all lines containing {$line}
found withing file.txt
:
sed -i "/{$pattern}/d" ./file.txt
Currently, this deletes all of the lines in this sample file.txt
when $pattern
is set to "cat":
One day, the {cat} said to the {owl}, "What are you eating for breakfast, {owl}?"
The {owl} replied, "I am eating {cereal}. Would you like some, {cat}?"
"Yes, I would," replied the {cat}.
So the {cat} and the {owl} ate {cereal}.
I need to change this, such that it does not delete the first found line containing {$pattern}
, but only deletes all subsequent appearances found in later lines:
E.g., suppose file.txt
is this:
One day, the {cat} said to the {owl}, "What are you eating for breakfast, {owl}?"
The {owl} replied, "I am eating {cereal}. Would you like some, {cat}?"
"Yes, I would," replied the {cat}.
So the {cat} and the {owl} ate {cereal}.
If $pattern
were set to "cat", the output would look like this, because line 1 has the first occurrence of "cat", and all other later lines also have it, so they are all deleted:
One day, the {cat} said to the {owl}, "What are you eating for breakfast, {owl}?"
If $pattern
were set to "owl", the output would look like this, because line 1 contains the first occurrence of "owl", and lines 2 and 4 also have instances, which are deleted:
One day, the {cat} said to the {owl}, "What are you eating for breakfast, {owl}?"
"Yes, I would," replied the {cat}.
If $pattern
were set to "cereal", the output would look like this with line 4 deleted, because line 4 is the only one with an additional occurrence of "cereal".
One day, the {cat} said to the {owl}, "What are you eating for breakfast, {owl}?"
The {owl} replied, "I am eating {cereal}. Would you like some, {cat}?"
"Yes, I would," replied the {cat}.
- The file must not be sorted, as the order of lines is important.
- Note that line 1 contains two copies of "owl", but the second appearance on that line is not regarded as the second appearance of "owl".
Is there any way to set sed
to not delete the line containing the first appearance of {$patter}
, but to only edit all later occurrences of a pattern?