LSN #5 Awk has Power

Sometimes it's easy to forget the power of awk. When faced with a task, it's often easy to resort to writing a program or script. This isn't a bad thing, but realizing some tasks can be handled with awk, could save you time.

Awk is good at taking lines of text and splitting them into columns. By default awk uses spaces as field separators. But, if our data was separated by something else, like a comma. We could specify that with "-F" or say its a tab separating the data, we could use "/t". Using something like $1, $2 or $3, we can get awk to select that column.

#Example of grabbing the first column 
awk '{print $1 }' temps.csv 

Awk commands are reletivly simple. Its just a simple program that iterates over your file, line by line. You then specify a pattern and if it matches, some action is performed. Basically its an IF statement, but since its so common, you would actually get an error in you used them.

#Example of the pattern match to do something 

awk '(PATTERN1){..print something} (PATTERN2){..print something}' temps.csv

#Real command - Checks every line in the file and will only return 2 lines, since thats all a file can have. 

awk '(NR==1){print "This is line one:" $0} (NR==2){print "This is line two:" $0}' temps.csv