Saturday, December 12, 2009

Simple Awk Usages

Say that you are logged into a bash terminal session on a local linux box. You have been asked to extract some information from a text file that is on the system. The text file could be 100,000 records long. For this example it has a header line and 3 data lines. The contents of the file are as follows

awk@intro > cat test.txt
User Phone Zip
tom 555-555-5553 55555
larry 555-555-5552 99999
daryl 555-555-5511

Now, the problem that we have is that we need to take this file and re-arrange the information to best fit our needs. The phone number needs to be the first thing that we see followed by the username. The zip code should be left out of this report. How can we easily accomplish this task?

Enter Awk.

awk@intro > awk ' { print $2" "$1 } ' test.txt
Phone User
555-555-5553 tom
555-555-5552 larry
555-555-5511 daryl

That was easy. Awk splits the file into numbered variables for the columns inside of test.txt. Since we want the phone number first we tell awk print $2" "$1 which gives us the second column, a space, and the first column. This job is done, that was easy.

No comments:

Post a Comment