Reputation: 1677
There are a few different ways of setting awk's field separator. These include
-F
: e.g. awk -F '\t' '{…}' a.txt
FS
variable at the beginning of the script: e.g. awk 'BEGIN {FS="\t"} {…} a.txt
FS
variable with the option -v
: e.g. awk -v 'FS=\t' '{…}' a.txt
However, I often use the following: awk '{…}' FS='\t' a.txt
(I like it because it's quick to type, and also allows for OFS='\t'
in a similar format.)
I've noticed that the field separator won't be set if the last two items are reversed. i.e. awk '{…}' a.txt FS='\t'
What does this syntax mean exactly? Hence, why is the order of the last two items so important?
Upvotes: 1
Views: 235
Reputation: 212198
awk
processes its arguments in order. Consider:
awk 'BEGIN{ print "BEGIN:", a }
{ print FILENAME":", a }
END { print "END:", a }
' file1 a=foo file2 a=bar
In this example, awk
first parses the script and executes the BEGIN blocks before it even reads its arguments. It then processes file1
, then makes the variable assignment a=foo
, then process file2
, then makes the variable assignment a=bar
, and finally processes the END
blocks.
The first argument (loosely defining "argument" as elements of the command line that are not flags) passed to awk
(assuming the absence of a -f
flag) is the script to be executed. The arguments following the script that contain an equals sign are variable assignments that are made after any BEGIN blocks and before input lines are processed for files listed after the assignment. Arguments that do not contain an equal sign are files to be processed. So:
awk '{...}' a.txt FS='\t'
does not work because the argument FS='\t'
is a variable assignment that is made after a.txt
is processed. Since no files are listed after the assignment, it is never relevant to the processing.
Upvotes: 2
Reputation: 41446
Last input on awk
need to be the file. That is why:
awk '{…}' a.txt FS='\t' # this does not work
awk '{…}' FS='\t' a.txt # this is OK
cat a.txt | awk '{…}' FS='\t' # this is OK too
awk '{…}' FS='\t' a.txt b.txt c.txt # multiple file input OK
Upvotes: 0