|
|
|
|
|
by deuill
3624 days ago
|
|
Awk is actually very intuitive once you learn the basics (should take about an hour). Awk is essentially a line-oriented pattern matching language, that is, a collection of patterns -> actions that are applied to every line of input. Syntax is very similar to C, but feels much more lightweight. To decompose the example above: NR > 1 {
print $1, $4
}
There are two parts to this, the pattern (the part outside the brackets), and the action (the part inside the brackets). Every line parsed is split into fields and stored in $1..$NR, where NR is the number of fields. The entire line is also available in the $0 variable. The default separator is the space character, though that can be changed.So, knowing the above semantics, the meaning of the above example should be clear: If the number of fields for this line is larger than 1, print the first and fourth field of the line. It's a very powerful paradigm, and you can do crazy stuff with Awk. Examples are an x86 assembler [0] and a SASS-style CSS preprocessor [1] (plugging myself there a bit). Unix coreutils are very powerful once you're familiar with them. [0]: http://doc.cat-v.org/henry_spencer/amazing_awk_assembler/
[1]: https://github.com/deuill/fawkss |
|
$NR stores the number of records (or the current record number) not the number of fields (that's $NF). In the example the "NR > 1" is meant to exclude the header line from the output.