Posted by: isaraffee | February 6, 2010

Exploring awk

Exploring awk

Prepare a file which has the following contents.

# cat employees

Tom Jones 4424 5/12/66 543355 A

Sally Adam 4676 5/10/76 545785 D

Jonas Bro 4624 7/12/66 533355 A

Tina Turner 7741 2/12/86 588855 D

Isasa Tan 5554 8/12/73 777755 A

With that,let’s run some awk commands. Alterntively, you can also use nawk command

# nawk ‘/Isasa/’ employees

Isasa Tan 5554 8/12/73 777755 A

# awk ‘/D/’ employees

Sally Adam 4676 5/10/76 545785 D

Tina Turner 7741 2/12/86 588855 D

# awk ‘/D/{print $1,$3}’ employees

Sally 4676

Tina 7741

Now let’s look at the command format.

awk ‘pattern’ filename

awk ‘action’ filename

awk ‘pattern {action}’ filename

Let’s see more examples

# awk ‘/D/{print NR,$0}’ employees

2 Sally Adam 4676 5/10/76 545785 D

4 Tina Turner 7741 2/12/86 588855 D

In the example above, NR will print the record number. $0 will print all fields of a record.

# awk ‘$6 ~ “A”‘ employees

Tom Jones 4424 5/12/66 543355 A

Jonas Bro 4624 7/12/66 533355 A

Isasa Tan 5554 8/12/73 777755 A

In the example above, the command will filter records which has value “A” in the 6th field. By default if no action is specified, all fields will be printed.

You can also specify the fields such as the one shown below:

# awk ‘$6 ~ “A”{print $1, $2}’ employees

Tom Jones

Jonas Bro

Isasa Tan

Instead of using the tilde sign (~), you can also replace it with the equal sign as shown below:

# awk ‘$6 == “A”{print $0}’ employees

Tom Jones 4424 5/12/66 543355 A

Jonas Bro 4624 7/12/66 533355 A

Isasa Tan 5554 8/12/73 777755 A

In the exmaple below, use a pair of forward slashes to filter records which has value A in the 6th field.

# nawk ‘$6 ~ /A/’ employees

Tom Jones 4424 5/12/66 543355 A

Jonas Bro 4624 7/12/66 533355 A

Isasa Tan 5554 8/12/73 777755 A

And if we want to sort the records above by the first field, pie it tp the sort command

# nawk ‘$6 ~ /A/’ employees | sort

Isasa Tan 5554 8/12/73 777755 A

Jonas Bro 4624 7/12/66 533355 A

Tom Jones 4424 5/12/66 543355 A

If you want to sort by the 5th field, type:

# nawk ‘$6 ~ /A/’ employees | sort -k5

Jonas Bro 4624 7/12/66 533355 A

Tom Jones 4424 5/12/66 543355 A

Isasa Tan 5554 8/12/73 777755 A

You can also do reverse sort of the 5th column by typing:

# nawk ‘$6 ~ /A/’ employees | sort -rn -k5

Isasa Tan 5554 8/12/73 777755 A

Tom Jones 4424 5/12/66 543355 A

Jonas Bro 4624 7/12/66 533355 A

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: