awk — processing columns
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
awk is a whole little language for tables. It reads the input line by line and splits each line into fields:
awk '{ print $1 }' file # the first field of each line
awk '{ print $2, $1 }' file # swap the columns
awk -F, '{ print $2 }' data.csv # the separator is a comma
awk '$3 > 100' file # lines where the third field is greater than 100
awk '{ sum += $2 } END { print sum }' file # the sum of the second column
Built-in variables:
$0 |
the whole line |
$1, $2… |
the fields |
NF |
the number of fields ($NF — the last field) |
NR |
the line number |
FS |
the field separator (the same as -F) |
An awk program is pairs of condition { action }. No condition — the action runs for every line. No action — the line is printed. The BEGIN { } and END { } blocks run before the first line and after the last one.
printf in awk works as in C: awk '{ printf "%-10s %5.1f\n", $1, $2 }'.
Task. The input is a table of name score (separated by a space). Print the names of those with more than 80 points, and on the last line — average: N, the average score of everyone with one decimal place.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.