How to remove every other line with sed?

Solution 1:

GNU sed has a suitable addressing mode:

sed -n '1~2!p' file

which means, starting from line 1, and with step 2, print all other lines.

Equivalently, you can drop the -n, and delete matching lines:

sed '1~2d'

It can also be done using awk:

awk 'NR%2==0' file

(Whenever line number is a multiple of 2, print the line)

Solution 2:

Here is the shortest I can think of:

sed -n 'g;n;p' file

It should work with non-GNU versions of sed (as well as GNU sed).

Solution 3:

This works with GNU and BSD (mac) versions of sed:

To remove odd lines (print even rows):

sed -n ’n;p’ file

Might look a bit confusing, so here is what happens under the hood step by step:

  1. sed: reads in first line
  2. -n: suppress output of first line
  3. n: output is suppressed, so don’t write anything out
  4. n (again): read next (second) line to pattern buffer, i.e. to process immediately
  5. p: print anything available in the pattern buffer overriding suppressed output, i.e. the 2nd line
  6. sed: reads in third line, since second line got already processed thanks to “n” in step4
  7. -n: suppress output of third line
  8. ...
  9. ...

To remove even lines (print odd rows):

sed -n ‘p;n’ file

Here is what happens under the hood algorithmically:

  1. sed: reads in first line
  2. -n: suppress output of first line
  3. p: prints content of pattern buffer, i.e. the first line, overriding suppressed output
  4. n: output is suppressed, so don’t write anything out
  5. n (again): read in next (second) line to pattern buffer for immediate processing, but since there are no more commands, nothing happens
  6. sed: reads in third line, since second line got already “processed” thanks to “n” in step5
  7. -n: suppress output of third line
  8. p: prints third line overriding suppressed output
  9. ...

Solution 4:

Perl solution:

perl -ne 'print if $. % 2 == 0' file

$. is the line number

Solution 5:

One more awk :

awk getline file