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

Sed/Awk to delete first, third, fifth… occurence of new line – platform independent

hi all im trying to make this

2022-11-14 18:49:59             Indicator is < 3    
1       No
2022-11-14 18:49:59             Indicator is < 10   
1       No
2022-11-14 18:49:59             Indicator is < 22   
1       No
2022-11-14 18:49:59             Indicator is < 1    
1       No

into

2022-11-14 18:49:59             Indicator is < 3    1       No
2022-11-14 18:49:59             Indicator is < 10   1       No
2022-11-14 18:49:59             Indicator is < 22   1       No
2022-11-14 18:49:59             Indicator is < 1    1       No

i found that you can use sed 's/something/some//2' for every second encounter but how to make it for 1st, 3th, 5th,…. and so one

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

>Solution :

Try this with awk using modulo.

$ awk 'NR % 2 == 0{print prev, $0} {prev = $0}' file
2022-11-14 18:49:59             Indicator is < 3     1       No
2022-11-14 18:49:59             Indicator is < 10    1       No
2022-11-14 18:49:59             Indicator is < 22    1       No
2022-11-14 18:49:59             Indicator is < 1     1       No

It looks at the record number NR and calculates modulo 2 of it. Since every second line comes out as 0 it will then print the previous prev and the current $0 line.

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