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

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


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.


How about perl?

perl -n -e '$.%10==0&&print'       # print every 10th line


You could possibly do it with sed, e.g.

sed -n -e 'p;N;d;' file # print every other line, starting with line 1

If you have GNU sed it's pretty easy

sed -n -e '0~10p' file # print every 10th linesed -n -e '1~2p' file # print every other line starting with line 1sed -n -e '0~2p' file # print every other line starting with line 2