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:
- sed: reads in first line
- -n: suppress output of first line
- n: output is suppressed, so don’t write anything out
- n (again): read next (second) line to pattern buffer, i.e. to process immediately
- p: print anything available in the pattern buffer overriding suppressed output, i.e. the 2nd line
- sed: reads in third line, since second line got already processed thanks to “n” in step4
- -n: suppress output of third line
- ...
- ...
To remove even lines (print odd rows):
sed -n ‘p;n’ file
Here is what happens under the hood algorithmically:
- sed: reads in first line
- -n: suppress output of first line
- p: prints content of pattern buffer, i.e. the first line, overriding suppressed output
- n: output is suppressed, so don’t write anything out
- n (again): read in next (second) line to pattern buffer for immediate processing, but since there are no more commands, nothing happens
- sed: reads in third line, since second line got already “processed” thanks to “n” in step5
- -n: suppress output of third line
- p: prints third line overriding suppressed output
- ...
Solution 4:
Perl solution:
perl -ne 'print if $. % 2 == 0' file
$.
is the line number
Solution 5:
One more awk :
awk getline file