AWK - fun with data - only print certain columns of data
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:
- Take nth column in a text file - I used the second answer by Tom van der Woerdt
- lots of good help here in How to use 'awk' to print columns from a text file (in any order) - this is where I got the field seperator
- 4 Awk If Statement Examples (if, if else, if else if, :? ) - forgot how to actually do a stand-alone awk script, so this was helpful. Also, how to use conditionals was another good thing.
- How To Use awk in Bash Scripting
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.