The first time I heard about ‘awk’ was from an interview. After that, I took a quick look at this stuff and left it alone. Recently, I’ve got a chance to know it well. It is a C style programming language used to manipulate regularly formatted text (like Database dumps and System log files). The utility scans each line of a file, looking for patterns that match those given on the command line. If a match is found, it takes the next programming step. If not, it then proceeds to the next line.

Syntax: awk ‘{pattern + action}’ (filenames)

where pattern represents what AWK is looking for in the data, and action is a series of commands executed when a match is found.

My first try of awk:

#awk ‘{ print }’ /etc/passwd

Then the content of file passwd showed up. Yeah, that’s it. Simple, clean, easy!

Another try:

#awk ‘{ print $0 }’ /etc/passwd

In awk, $0 –>the current line, so print=print $0. If I try:

#awk ‘{ print “ILOVETHISGAME” }’ /etc/passwd

Ha, what did I get?! Not the file passwd, I saw ILOVETHISGAME everywhere instead. Cool!

To print specific fields in output. Awk works pretty well and efficient.

#awk -F”:” ‘{ print $1 }’ /etc/passwd

Note: -F defines “:” as field separator; print $1–>it prints the first field in each line of the input file. E.g:

#awk -F”:” ‘{ print $1 $3}’ /etc/passwd

Yeah, as your wish, awk will print out the 1st and the 3rd field(username and uid). But when I run it, it’s not perfect because there was no SPACE between username and uid. Later, I figured it out:

# awk -F”:” ‘{ print $1 ” ” $3 }’ /etc/passwd

That’s it!

There are a bunch of functions which are suitable for the different types of output. If you know the tricks, you make the deal. For example, it’s very suitable to make report form (especially in some special formatted cases)!