Tutorial by Examples

Processing tabular data with awk is very easy, provided that the input is correctly formatted. Most software producing tabular data use specific features of this family of formats, and awk programs processing tabular data are often specific to a data produced by a specific software. If a more gener...
Given a file using ; as a column delimiter. Permuting the first and the second column is accomplished by awk -F';' -v 'OFS=;' '{ swap = $2; $2 = $1; $1 = swap; print }'
Given a file using ; as a column delimiter. We compute the mean of the values in the second column with the following program, the provided input is the list of grades of a student group: awk -F';' '{ sum += $2 } END { print(sum / NR) }' <<EOF Alice;2 Victor;1 Barbara;1 Casper;4 Deborah;...
We assume a file using ; as a column delimiter. Selecting a specific set of columns only requires a print statement. For instance, the following program selects the columns 3, 4 and 7 from its input: awk -F';' -v 'OFS=;' '{ print $3, $4, $7 }' It is as usual possible to more carefully choose lin...
Given a file using ; as a column delimiter. We compute the median of the values in the second column with the following program, written for GNU awk. The provided input is the list of grades of a student group: gawk -F';' '{ sample[NR] = $2 } END { asort(sample); if(NR % 2 == 1) { p...
Pattern matching can be used effectively with awk as it controls the actions that follows it i.e. { pattern } { action }. One cool use of the pattern-matching is to select multiple between two patterns in a file say patternA and patternB $ awk '/patternA/,/patternB/' file Assume my file contents...

Page 1 of 1