DEV Community

suzuki-navi
suzuki-navi

Posted on

How to Extract Every Nth Line from a Text File

To output every fifth line starting from the first line, sixth line, eleventh line, and so on,

$ sed -ne 1~5p < data.txt
$ awk NR%5==1 < data.txt
$ perl -nle '$.%5==1 && print' < data.txt
$ ruby -nle '$.%5==1 && print' < data.txt
Enter fullscreen mode Exit fullscreen mode

To output every fifth line starting from the fifth line, tenth line, fifteenth line, and so on,

$ sed -ne 0~5p < data.txt
$ awk NR%5==0 < data.txt
$ perl -nle '$.%5==0 && print' < data.txt
$ ruby -nle '$.%5==0 && print' < data.txt
Enter fullscreen mode Exit fullscreen mode

At first glance, Perl and Ruby may appear to be the same.

Top comments (0)