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

How to delete lines if next line begins with the same content?

As an example the file with following content:

My dog
My dog is running
My dog is running fast
A cat
A cat is black
A cat is black and small

As a result I want to have only this two lines:

My dog is running fast
A cat is black and small

I would prefer to do it in one line command.

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

Tried many SED, AWK and UNIQ options but could not find a good solution.
I guess SED should be able to do it if it can read lines by two and print first line only if second line does not match it. But, cannot figure out how to do it.

>Solution :

The following seems to work:

sed -n ':a;$!N;s/^\([^\n]*\)\n\1/\1/;$!ta;P;D'
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