0
0
Bash Scriptingscripting~5 mins

awk field extraction in scripts in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does $1 represent in an awk command?

$1 represents the first field (or column) of the current line being processed by awk.

Click to reveal answer
beginner
How do you print the third field of each line using awk?

Use awk '{print $3}' filename to print the third field of each line.

Click to reveal answer
beginner
What is the default field separator in awk?

The default field separator is any whitespace (spaces or tabs).

Click to reveal answer
intermediate
How can you change the field separator to a comma in awk?

Use the -F option like this: awk -F',' '{print $2}' filename to split fields by commas.

Click to reveal answer
intermediate
In a script, how do you store the second field of a line into a variable using awk?

You can use command substitution: var=$(awk '{print $2}' filename). This stores the second field output into the shell variable var.

Click to reveal answer
What does awk '{print $1}' file.txt do?
APrints the whole line
BPrints the last field of each line
CPrints the first field of each line in file.txt
DDeletes the first field
How do you tell awk to split fields by a colon :?
Aawk -S':' '{print $2}' file
Bawk -F':' '{print $2}' file
Cawk --field=':' '{print $2}' file
Dawk -D':' '{print $2}' file
If a line is apple orange banana, what does $3 represent?
Abanana
Borange
Capple
DThe whole line
Which command prints the second and fourth fields separated by a space?
Aawk '{print $2+$4}' file
Bawk '{print $2.$4}' file
Cawk '{print $2-$4}' file
Dawk '{print $2, $4}' file
What is the output of awk -F',' '{print $1}' on the line red,green,blue?
Ared
Bgreen
Cblue
Dred,green,blue
Explain how awk extracts fields from a line and how you can change the field separator.
Think about how words in a sentence are split by spaces or other characters.
You got /3 concepts.
    Describe how to use awk inside a bash script to save a specific field from a file into a variable.
    Remember how you capture command output in bash.
    You got /3 concepts.