Wednesday, December 12, 2012

How to print every nth line in a file in Linux?

How to print every nth line of a file?  The requirement is to print every 3rd line of the file.
  Let us consider a file with the following content.
$ cat file
1. Using awk :
$ awk '!(NR%3)' file
  NR variable contains the line number of the file in awk. If NR modulus 3 is equal to 0, it indicates the line is a multiple of 3. And only those lines are printed which modulus is 0.

2. Using sed:
$ sed -n 'n;n;p;' file
  n command in sed prints the current line(if -n is not present) and reads the next line in the buffer. Since -n switch is present, the n command does not print. Hence, after the 'n;n;', the 3rd line is present in the pattern space and it is printed using the p command. And this repeats till the end of the file, and hence every 3rd line gets printed.

3. Using Perl:
$ perl -lne '$.%3 or print;' file
  This is same as awk solution. The $. variable in Perl is equivalent to awk's NR. Only those lines are printed whose modulus is not equal to 0.

4. Bash shell script:

while read line
   [ $x -eq 3 ] && { echo $line ; x=0;}
done < file
 This is a pure shell solution without any external command. And hence for big files, this solution will be much better in performance. Using the while loop, every line of the file is read into the "line" variable. And internally, a counter 'x" is incremented, and the line is printed only when 'x' reaches 3 after which the counter is reset to 0.
Related Posts Plugin for WordPress, Blogger...

No comments:

Post a Comment