Bash Awk
Awk is a tool that works on text split into fields. A field is one word on a line, counted from the left.
Printing the first field
The print $1 action takes the first word of each line. Only the three names come out.
echo "Ana 90" > scores.txt
echo "Ben 75" >> scores.txt
echo "Cid 60" >> scores.txt
awk '{print $1}' scores.txtPrinting the second field
Asking for $2 picks the second word of each line. This time only the scores come out.
echo "Ana 90" > scores.txt
echo "Ben 75" >> scores.txt
echo "Cid 60" >> scores.txt
awk '{print $2}' scores.txtPrinting two fields together
The comma prints a space between the two fields. Each line shows a name and a score, with the subject left out.
echo "Ana math 90" > lessons.txt
echo "Ben art 75" >> lessons.txt
echo "Cid music 60" >> lessons.txt
awk '{print $1, $3}' lessons.txtExample
echo "Ana 90" > scores.txt
echo "Ben 45" >> scores.txt
echo "Cid 60" >> scores.txt
echo "Ben 30" >> scores.txt
echo "Scores above 50:"
awk '$2 > 50' scores.txtKey points
- Awk splits each line into fields at the spaces.
- The name $1 stands for the first field on a line.
- The name $2 stands for the second field on a line.
- Print two fields by listing them with a comma between them.
- A condition before the braces tests each line first.
- Awk runs the print action only on lines that pass the test.
In this example, the scores file holds a name and a score on each line. The condition $2 > 50 tests the second field of every line. Only the lines for Ana and Cid pass, so only their lines are printed.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
In the line 'Ana math 90', what does awk print for $3?