Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete every Xth line in a text file?

Tags:

text

bash

Consider a text file with scientific data, e.g.:

5.787037037037037063e-02 2.048402977658663748e-01 1.157407407407407413e-01 4.021264347118673754e-01 1.736111111111111049e-01 5.782032163406526371e-01 

How can I easily delete, for instance, every second line, or every 9 out of 10 lines in the file? Is it for example possible with a bash script?

Background: the file is very large but I need much less data to plot. Note that I am using Ubuntu/Linux.

like image 396
Ingo Avatar asked Mar 27 '12 17:03

Ingo


People also ask

How do you delete all occurrences of a list of words from a text file?

I would recommend that you do a Ctrl+F (PC) Command+F (Mac) find all "Ref" and replace with empty string (in other words leave the replace box empty). Hit enter and all done! Hope this helps!


1 Answers

This is easy to accomplish with awk.

Remove every other line:

awk 'NR % 2 == 0' file > newfile 

Remove every 10th line:

awk 'NR % 10 != 0' file > newfile 

The NR variable in awk is the line number. Anything outside of { } in awk is a conditional, and the default action is to print.

like image 105
jordanm Avatar answered Oct 06 '22 17:10

jordanm