AWK to print the nth line from a file

I want to print every Nth line of a file using AWK. I tried changing the general format: -

awk '0 == NR % 4' results.txt

so that: -

 awk '0 == NR % $ct' results.txt 

where 'ct' is the number of lines to be skipped. this does not work. can anyone help me? Thanks in advance.

+7
awk
source share
3 answers

You can use:

 awk -v patt="$ct" 'NR % patt' results.txt 

Explanation

For a file like the following:

 $ cat -na 1 hello1 2 hello2 3 hello3 4 hello4 5 hello5 ... 37 hello37 38 hello38 39 hello39 40 hello40 

They are equivalent:

 $ awk 'NR % 7 == 0' a hello7 hello14 hello21 hello28 hello35 $ ct=7 $ awk -v patt="$ct" 'NR % patt == 0' a hello7 hello14 hello21 hello28 hello35 

Or even

 $ awk -v patt="$ct" '!(NR % patt)' a 

Note that the syntax NR % n == 0 means: the number of lines is multiple in n . If we say !(NR % patt) , then this is true when NR % patt is false, i.e. NR is a multiple of patt .

Update

As you comment, you are using Solaris instead of the standard awk use the following:

 /usr/xpg4/bin/awk 
+9
source share

How about this:

 awk -vn="$ct" '0 == NR % n' results.txt 

or a little shorter

 awk -vn="$ct" '!(NR % n)' results.txt 
+4
source share

It also works, but it is not a good practice.

 awk '!(NR%'$ct')' results.txt 

It is normal to use:

 awk '!(NR%n)' n="$ct" results.txt 
+1
source share

All Articles