Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove every other line with sed?

Tags:

sed

How can I remove every odd line, using sed?

remove
keep
remove
keep
remove
...
like image 598
hhh Avatar asked Apr 01 '10 12:04

hhh


People also ask

How do I delete a sed matching line?

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.

How do you use sed to replace multiple lines?

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.


3 Answers

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)

like image 186
ghostdog74 Avatar answered Oct 20 '22 16:10

ghostdog74


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).

like image 39
Dennis Williamson Avatar answered Oct 20 '22 17:10

Dennis Williamson


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. ...
like image 45
balanyo Avatar answered Oct 20 '22 18:10

balanyo