Home > Mobile >  How the awk's body statement execute?
How the awk's body statement execute?

Time:07-24

:~$ 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.

CodePudding user response:

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.(...)

CodePudding user response:

Structure of an awk program in a nutshell:

[BEGIN{[code]}]        # executed before any input is read
[condition][{action}]  # if exists, condition is evaluated for each input record
                       # for true or non-existent conditions action, if exists, is performed
[END{[code]}]          # executed after all input is read and processed 
                       # or if exit was called
  • Related