Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWK to print every nth line from a file

Tags:

awk

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

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

to:-

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

where 'ct' is the number of lines that should be skipped. its not working . can anyone please help me out? Thanks in advance.

like image 915
Shreedhar Avatar asked Aug 21 '13 08:08

Shreedhar


People also ask

What is awk '{ print $3 }'?

I. If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output.


2 Answers

You may want to use:

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

Explanation

Given a file like the following:

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

These 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: number of line is multiple to n. If we say !(NR % patt), then this is true whenever NR % patt is false, ie, NR is multiple of patt.

Update

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

/usr/xpg4/bin/awk
like image 195
fedorqui 'SO stop harming' Avatar answered Oct 02 '22 09:10

fedorqui 'SO stop harming'


How about this:

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

or a bit shorter

awk -v n="$ct" '!(NR % n)' results.txt
like image 31
user000001 Avatar answered Oct 02 '22 10:10

user000001