How to delete every second line from a file?

Solving this by deleting every second line can be error prone (for example, when process sometimes generates two meaningful lines instead one). May be it is better to filter out the garbage:

grep -v "No error occurred" file

It can run as filter, you can add more garbage patterns here and improve the result.


With sed:

sed -e n\;d <file

With POSIX awk:

awk 'FNR%2' <file

If you have older awk (like oawk), you need:

oawk 'NR%2 == 1' <file

With ex:

$ ex file <<\EX
:g/$/+d
:wq!
EX

will edit the file in-place.

  • g mark a global command
  • /$/ match every lines
  • +d delete the next line
  • wq! save all changes

This approach share the same ideal with sed approach, delete every next line of current line start from line 1.

With perl:

perl -ne 'print if $. % 2' <file

and raku:

raku -ne '.say if $*IN.ins % 2' <file
raku -ne '.say if ++$ % 2' <file

Edit

Raku IO::Handle.ins was removed in this commit.


Ассоrding to the question, with GNU sed:

sed '0~2d' file

will delete every second line but I'd like to offer filter lines by it content:

sed '/Data/! d' file

or with same result

sed '/No error/d' file