Shell Columns with Awk
awk splits each line into columns. A column is one piece of a line, split by spaces or another separator.
Print the first column
awk prints the first word of each line in notes.txt.
awk '{print $1}' notes.txtPrint the second column
awk prints the second word of each line.
awk '{print $2}' notes.txtSplit on commas
-F, splits each CSV line on commas, and awk prints the first column.
awk -F, '{print $1}' data.csvPrint two columns
awk prints the age and the city from each CSV line.
awk -F, '{print $2, $3}' data.csvExample
awk '{print $1}' notes.txt
awk -F, '{print $1, $3}' data.csvKey points
- Use $1 for the first column, $2 for the second, and so on.
- Use print to print the columns awk picks.
- Use -F to change the separator, like a comma in a CSV file.
- The awk program sits in single quotes, so the shell passes it to awk unchanged.
- CSV: a file where commas split each line into columns.
In this example, the first awk prints the first word of each line in notes.txt. The second awk splits the CSV lines on commas and prints the name and the city.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
In awk, what does $2 mean?