How the awk's body statement execute?

Issue

:~$ awk -F"," '{print $0}' sample.csv
c1,c2,c3
1,2,3
4,5,6
7,8,9
10,11,12

The above awk command print the csv file content. I don’t have any doubt in the above command.

:~$ awk -F"," '{print "=====This is table====="}{print $0}' sample.csv
=====This is table=====
c1,c2,c3
=====This is table=====
1,2,3
=====This is table=====
4,5,6
=====This is table=====
7,8,9
=====This is table=====
10,11,12

But in the above command I expect after the "=====This is table=====" statement the table will print. But the print statement interrupt in every row of the table.

=====This is table=====
c1,c2,c3
1,2,3
4,5,6
7,8,9
10,11,12

But I expect like this. I need explanation of why the print statement printed inside the table content !!.

:~$ awk -F"," 'BEGIN{print "This is table"}{print $0}' sample.csv
This is table
c1,c2,c3
1,2,3
4,5,6
7,8,9
10,11,12

I know if we give the print statement in BEGIN and END statement ,it will print only one time. If i give any print statement in body statement it will print multiple times. Please explain.

Thanks in advance.

Solution

I need explanation of why the print statement printed inside the table
content

From gawk man page

(…)For each record in the input, gawk tests to see if it matches any
pattern in the AWK program. For each pattern that the record matches,
the associated action is executed. The patterns are tested in the
order they occur in the program.(…)Normally, records are separated
by newline characters.(…)

Answered By – Daweo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published