awk Getting started with awk How to run AWK programs


If the program is short, you can include it in the command that runs awk:

awk -F: '{print $1, $2}' /etc/passwd

In this example, using command line switch -F: we advise awk to use : as input fields delimiter. Is is the same like

awk 'BEGIN{FS=":"}{print $1,$2}' file

Alternativelly, we can save the whole awk code in an awk file and call this awk programm like this:

awk -f 'program.awk' input-file1 input-file2 ...

program.awk can be whatever multiline program, i.e :

# file print_fields.awk
BEGIN {print "this is a header"; FS=":"}
{print $1, $2}
END {print "that was it"}

And then run it with:

awk -f print_fields.awk /etc/passwd   #-f advises awk which program file to load

Or More generally:

awk -f program-file input-file1 input-file2 ...

The advantage of having the program in a seperate file is that you can write the programm with correct identation to make sense, you can include comments with # , etc