SamuelNLP SamuelNLP - 3 months ago 14x
Linux Question

remove odd or even lines from text file in terminal in linux

I need to remove odd lines in a text file to make a down-sampling. I've found this command,

awk 'NR%2==0' file

but it only prints the odd lines in the terminal. How to really remove them?

I don't really care for even or odd, I want them removed from the file or printed in another file. This only prints them in the terminal.



The % is a modulus operator and NR is the current line number, so NR%2==0 is true only for even lines and will invoke the default rule for them ({ print $0 }). Thus to save only the even lines, redirect the output from awk to a new file:

awk 'NR%2==0' infile > outfile


You can accomplish the same thing with sed. devnulls answer shows how to do it with GNU sed. Below are alternatives for versions of sed that do not have the ~ operator:

remove even lines

sed 'n; d' infile  # output ODD lines only

remove odd lines

sed '1d; n; d' infile  # output EVEN lines only