How can I remove every odd line, using sed?
remove
keep
remove
keep
remove
...
To begin with, if you want to delete a line containing the keyword, you would run sed as shown below. Similarly, you could run the sed command with option -n and negated p , (! p) command. To delete lines containing multiple keywords, for example to delete lines with the keyword green or lines with keyword violet.
By using N and D commands, sed can apply regular expressions on multiple lines (that is, multiple lines are stored in the pattern space, and the regular expression works on it): $ cat two-cities-dup2.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With