I want to completely remove lines containing a pattern ignoring first few lines. I tried:
$ sed -i '2,$s/pattern/d' file.txt
but it says unterminated's' command.
For example I have a file:
pattern # important one, not to be removed
some line1
some line2
pattern some content
another line3
pattern another content
another line4
So, I want
pattern # important one, not to be removed
some line1
some line2
another line3
another line4
If I use sed -i '2,$s/pattern//' file.txt then it doesn’t completely remove the line, there are characters that aren’t in pattern, even though it must be removed.
>Solution :
The easiest way to do this in sed would probably be to skip the lines you want to ensure cannot be affected, instead of selecting the lines you want to consider, and then sub-selecting within those the ones you actually want to delete. Example:
sed '1b;/pattern/d' file.txt
Explanation:
That’s two independent rules , separated by a semicolon (;).
-
The first has address
1, which selects line 1 by line number, and commandb, which, in this form, ends the current sed cycle and starts a new one.sed‘s default behavior is to print its pattern space at the end of each cycle, before reading the next line, so this just passes the first line through. -
The second has address
/pattern/, which selects the lines you want to delete from among those not already skipped. Of course, thedcommand deletes them.
You could use any kind of address with the b command, not just line number, and you could put any number of them at the start of the sed expression to exclude diverse lines based on different criteria.