I am having a bit of trouble with a sed command. I need to delete the first 3 lines that contain a specified word from a file.
My sed command only checks the first 6 lines, whether or not they contain the word. It deletes the lines containing the word, but it stops after 6 lines, not after 3 lines that contain the word.
This is my command:
sed "1,6{/.*$word.*/d;}" "$filename"`
So, for example, I want to delete the first 3 lines containing the word "please", for the file content:
leave this line alone
leave this line alone
1 please delete this line
leave this line alone
2 please delete this line
leave this line alone
leave this line alone
3 please delete this line
leave this line alone
The output is:
leave this line alone
leave this line alone
leave this line alone
leave this line alone
leave this line alone
3 please delete this line
leave this line alone
As noted in the comments, an
awksolution is simple.For example:
or slightly more confusingly but more efficiently (since we can stop checking lines after we've found three matches):
It is not very convenient to try to count with
sed, although it is possible. Parameterising arguments is also complicated.Ignoring both those issues, here is a sed script to delete the first 3 occurrences of lines containing "please":
Like the second awk, we can avoid scanning lines after we have found enough matches:
Applying any script to:
produces: