How to remove every other line with sed?

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

How can I remove every odd line, using sed?

remove
keep
remove
keep
remove
...
5条回答
  •  Happy的楠姐
    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. ...

提交回复
热议问题