Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete line containing pattern in between specific range of lines

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 command b, 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, the d command 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading