How can I remove every odd line, using sed?
remove
keep
remove
keep
remove
...
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)
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
).
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:
To remove even lines (print odd rows):
sed -n ‘p;n’ file
Here is what happens under the hood algorithmically:
One more awk :
awk getline file
Perl solution:
perl -ne 'print if $. % 2 == 0' file
$.
is the line number