0
0
Linux CLIscripting~5 mins

awk patterns and actions in Linux CLI - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the basic structure of an awk command using patterns and actions?
An awk command has the form: awk 'pattern { action }' filename. The pattern selects lines, and the action tells awk what to do with those lines.
Click to reveal answer
beginner
In awk, what happens if you omit the pattern but provide an action?
If the pattern is omitted, awk applies the action to every line of the input file.
Click to reveal answer
beginner
What does the pattern /error/ mean in awk?
The pattern /error/ matches any line that contains the word 'error'. It uses regular expression matching.
Click to reveal answer
beginner
How do you print the first field of each line using awk?
Use the action { print $1 }. For example: awk '{ print $1 }' filename prints the first word of each line.
Click to reveal answer
intermediate
What does the pattern-action pair NR == 3 { print } do in awk?
It prints only the third line of the input. NR is the current line number, so when NR == 3, the action print runs.
Click to reveal answer
What does this awk command do? awk '/fail/ { print $2 }' file.txt
APrints all lines containing 'fail'
BPrints the second word of lines containing 'fail'
CPrints the second line of the file
DPrints the entire file
What happens if you run awk '{ print $0 }' file.txt?
APrints lines containing 'print'
BPrints only the first word of each line
CPrints nothing
DPrints the entire file line by line
Which pattern matches lines where the first field equals 'John'?
ANR == John
B/John/
C$1 == "John"
DJohn == $0
What does this command do? awk 'NR > 5' file.txt
APrints lines after the fifth line
BPrints the first five lines
CPrints lines containing '5'
DPrints nothing
How do you print the number of fields in each line using awk?
A{ print NF }
B{ print NR }
C{ print $NF }
D{ print $0 }
Explain how awk uses patterns and actions to process text files.
Think about how you pick certain lines and then decide what to do with them.
You got /4 concepts.
    Describe how to print the third field of lines containing the word 'error' using awk.
    Combine a pattern that finds 'error' and an action that prints a specific field.
    You got /3 concepts.