Bash Awk Fields and Formatting
Awk fields are the separate words or values on one input line. Formatting controls how those fields are split, joined, and lined up in the output.
Split on colons, join with commas
The -F option sets the input separator to a colon. OFS sets the output separator to a comma.
printf 'anna:30:paris\nben:25:rome\n' > people.txt
awk -F: 'BEGIN{OFS=","} {print $1,$3}' people.txtLine numbers and field counts
NR counts lines and NF counts fields on each line. The second line has only one field, so its NF is 1.
printf 'red green blue\nyellow\n' > colors.txt
awk '{print NR, NF, $1}' colors.txtFixed-width columns with printf
The %-8s layout left-aligns each name in eight spaces. The %04d layout pads each number with zeros to four digits.
printf 'apple 3\nbanana 12\n' > fruit.txt
awk '{printf "%-8s %04d\n", $1, $2}' fruit.txtExample
printf 'paris:france:2100000\nrome:italy:2800000\n' > cities.txt
awk -F: 'BEGIN{printf "%-8s %-8s %10s\n", "CITY", "COUNTRY", "POP"} {printf "%-8s %-8s %10d\n", $1, $2, $3}' cities.txtKey points
- FS: the input field separator that splits each line into fields.
- OFS: the output field separator placed between printed fields.
- NF: the number of fields on the current line.
- NR: the number of the current line, counted from the first line read.
- $1: the first field of the current line.
- printf: a statement that prints values in a fixed layout.
- Field reordering: printing fields in a new order, such as $3 before $1.
In this example, awk splits each line on colons. The BEGIN block prints the column headings before any input line is read. Each row then prints the city, the country, and the population, with the number right-aligned in ten spaces.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which variable holds the number of fields on the current line?