Delete every Nth line in shell
14,682
Solution 1
If you have GNU sed, you could use the n~m
(n
skip m
) address notation
sed '1~3d' file
which deletes every third line, starting at the first.
Solution 2
To select only lines modulo N
with awk
try
awk '!(NR%2)' file
or
awk 'NR%3==0' file
Here NR
denotes number of rows processed so far.
In your specific case (remove all lines with Y
):
$ echo 'YYYYYY
XXXXXX
XXXXXX
YYYYYY
XXXXXX
XXXXXX' | awk '!(NR%3==1)'
XXXXXX
XXXXXX
XXXXXX
XXXXXX
Related videos on Youtube
Author by
mormaii2
Updated on September 18, 2022Comments
-
mormaii2 over 1 year
I'm trying to delete a line after N lines using awk and I can't seem to get it right. The file format is like this
YYYYYY XXXXXX XXXXXX YYYYYY XXXXXX XXXXXX
The real example would be
office3 3 1 office3 6 1 office3 6 3 office3 1 1
How can I delete the YY lines or the lines that say "office". I need to delete a line every two lines regardless of their content.
-
Ciro Santilli Путлер Капут 六四事 almost 9 years
-
-
Angel Todorov over 9 yearsin this example, we want to delete lines 1 and 4, so
NR%3==1
-
mormaii2 over 9 yearsThis solved it for me. I didn't know abot that sed function. Thank you!
-
Stéphane Chazelas over 9 yearsThis solution has the advantage of being standard and portable to all POSIX systems (even pre-POSIX ones as except for the first one, it works in the original
awk
from 1979)