AWK - fun with data - only print certain columns of data

in «tip» by Michael Beard
Tags: , , , ,

how to use AWK to print/filter data

I needed to just print out some columns in a file to see if I was missing something or not, so ... AWK to the rescue.

Some useful urls:

Here is a simple command-line script to print the 2nd and 3rd column in a file:

awk '{ print $2 $3 }' myTextFile.txt

Of course, that didn't do what I wanted, as the file I was looking at was comma delimited, so ...

awk -F "," '{ print $2 $3 }' myTextFile.txt

That sort of did what I wanted (well, exactly, but too much data, so ...). Here is how to call it with using an AWK script file. Here is the file (called myAwkScript.awk):

{
    if ($3 == "" && $4 == "" ) {
        print $2 " : " $3 " - " $4;
    }
}

and to call it:

awk -F "," -f myAwkScript.awk myTextFile.txt

Then, as another example of trying to limit the data (as the above didn't print anything -- later I found out correctly):

{
    if ($2 == "" && ($3 != "AMER" && $3 != "ADVNCED")) { 
        print $1 " : " $2 " - " $3;
    }
}

then, I got something more like I needed.

So, anyway, AWK is a pretty handy way to filter out data when you need something quick.