0
0
Linux CLIscripting~10 mins

awk basics (field processing) in Linux CLI - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - awk basics (field processing)
Start: Read line from input
Split line into fields
Process fields using $1, $2, ...
Perform action (print, calculate, etc.)
Read next line or end if no more lines
Awk reads each line, splits it into fields, processes fields by position, then performs actions like printing.
Execution Sample
Linux CLI
echo "apple banana cherry" | awk '{print $2}'
Prints the second word (field) from the input line.
Execution Table
StepInput LineFields SplitField $1Field $2Field $3ActionOutput
1apple banana cherry[apple, banana, cherry]applebananacherryprint $2banana
2No more linesN/AN/AN/AN/AEnd
💡 No more input lines to process, awk stops.
Variable Tracker
VariableStartAfter 1Final
$1N/Aappleapple
$2N/Abananabanana
$3N/Acherrycherry
Key Moments - 2 Insights
Why does awk use $1, $2, $3 instead of variable names?
Awk automatically splits each input line into fields numbered $1, $2, $3, etc. This lets you access words by position without naming them. See execution_table row 1 where fields are split and assigned.
What happens if the input line has fewer fields than the number used?
If you try to access a field number that doesn't exist, awk returns an empty string. For example, if $3 doesn't exist, printing $3 outputs nothing. This is shown by the variable_tracker where fields are only set if present.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 1, what is the value of $3?
Aapple
Bcherry
Cbanana
DNo value
💡 Hint
Check the 'Field $3' column in execution_table row 1.
At which step does awk stop processing input?
AStep 2
BStep 1
CAfter Step 1
DNever stops
💡 Hint
Look at the 'Action' column in execution_table row 2.
If the input line was "dog cat", what would $3 be?
Adog
Bcat
Cempty string
Derror
💡 Hint
Refer to key_moments about missing fields returning empty strings.
Concept Snapshot
Awk reads input line by line.
Splits each line into fields by spaces.
Fields accessed by $1, $2, $3...
Use print $n to output fields.
If field missing, $n is empty string.
Processes until no more lines.
Full Transcript
Awk is a tool that reads text line by line. For each line, it splits the line into parts called fields, separated by spaces by default. Each field can be accessed by a number starting at 1, like $1 for the first word, $2 for the second, and so on. You can tell awk to do things with these fields, like print one of them. For example, printing $2 will show the second word of each line. If a line has fewer words than the number you ask for, awk gives an empty string for that field. Awk keeps doing this for every line until there are no more lines to read, then it stops.