Does an awk script or command execute itself to every line it reads?

0

I got an awk script named my_awk:

#!usr/bin/awk -f

{ 
if ($1 == "#START") { FS=":";} 
else if ($1 == "#STOP") { FS = " ";}
else { print $3} 
}

And I invoked it through:

cat my_file | awk -f my_awk

I'm new to awk so I'm ignorant about awk's mechanism. Will this my_awk script execute its command to the whole my_file or to each line of the file?

Zen

Posted 2014-06-17T13:25:01.753

Reputation: 187

Answers

2

When you pipe something to a script, the script will only be executed once. So, for example if you do:

foo | bar

then bar is called only once, with its STDIN being whatever foo wrote to STDOUT.

You have a useless use of cat there, since you could just do:

awk -f my_awk < my_file

Or, since awk can directly work with file name arguments:

awk -f my_awk my_file

If you go further, awk itself is a tool that works on line-by-line basis, but it's really called only once by the shell. From this tutorial:

Like most UNIX utilities, AWK is line oriented. That is, the pattern specifies a test that is performed with each line read as input.

slhck

Posted 2014-06-17T13:25:01.753

Reputation: 182 472

but how awk works of the file? The script I wrote above has successfully changed the FS separator for 2 different lines! – Zen – 2014-06-18T02:29:12.163

See my updated answer. – slhck – 2014-06-18T05:52:29.470