How to remove every other line with sed?

前端 未结 5 474
春和景丽
春和景丽 2020-12-04 14:16

How can I remove every odd line, using sed?

remove
keep
remove
keep
remove
...
相关标签:
5条回答
  • 2020-12-04 14:52

    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)

    0 讨论(0)
  • 2020-12-04 14:55

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

    0 讨论(0)
  • 2020-12-04 14:57

    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. ...
    0 讨论(0)
  • 2020-12-04 15:10

    One more awk :

    awk getline file
    
    0 讨论(0)
  • 2020-12-04 15:12

    Perl solution:

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

    $. is the line number

    0 讨论(0)
提交回复
热议问题