Top 20 Linux awk Command Questions & Answers
Question 1: Basic Field Printing
Question: What does the command awk '{print $1, $3}' file.txt do?
* A) Prints the 1st and 3rd lines of the file
* B) Prints the 1st and 3rd columns (fields) separated by space
* C) Prints character 1 and character 3 of every line
* D) Replaces column 1 with column 3
Answer: B
Explanation: By default, awk splits lines by whitespace and maps each segment to $1, $2, $3, etc. Comma separation in print outputs the Output Field Separator (default is space).
Question 2: Entire Record Selector
Question: Which built-in variable represents the entire current input line or record?
* A) $NF
* B) $0
* C) $1
* D) $*
Answer: B
Explanation: $0 holds the full line/record, whereas $1, $2, ... hold individual fields.
Question 3: Dynamic Last Field
Question: How do you print the last field of every row, regardless of how many columns are present?
* A) awk '{print $LAST}' file.txt
* B) awk '{print $(NF-1)}' file.txt
* C) awk '{print $NF}' file.txt
* D) awk '{print $(END)}' file.txt
Answer: C
Explanation: NF holds the number of fields in the current record. Referencing $ before NF ($NF) resolves to the value of the last field.
Question 4: Field Delimiter Flag
Question: Which command-line option changes the input field delimiter to a colon (:)?
* A) awk -d: '{print $1}' /etc/passwd
* B) awk -F: '{print $1}' /etc/passwd
* C) awk -s: '{print $1}' /etc/passwd
* D) awk -t: '{print $1}' /etc/passwd
Answer: B
Explanation: -F sets the Input Field Separator (FS). -F: tells awk to treat : as the column delimiter.
Question 5: Total Records vs File Records
Question: What is the primary difference between NR and FNR?
* A) NR counts fields; FNR counts rows
* B) NR is cumulative line count across all files; FNR resets to 1 for each new file
* C) FNR counts characters; NR counts lines
* D) There is no difference; they are aliases
Answer: B
Explanation: NR (Number of Records) tracks total lines processed across the entire run, while FNR (File Number of Records) tracks the line number relative to the file currently being processed.
Question 6: Output Delimiter Modification
Question: Given awk -F: 'BEGIN{OFS=" - "} {print $1, $7}' /etc/passwd, what does OFS do?
* A) Omits the first separator
* B) Sets the Output Field Separator between fields to " - "
* C) Filters out matching fields
* D) Specifies an output file stream
Answer: B
Explanation: OFS controls how fields printed with commas (like $1, $7) are joined in the output.
Question 7: Pre-Processing Blocks
Question: When does the BEGIN block execute?
* A) Once for each line read
* B) Before any input files or records are read
* C) Only when an error occurs
* D) After the last line is processed
Answer: B
Explanation: BEGIN { ... } runs once before any input stream processing begins, commonly used to initialize variables or headers.
Question 8: Summary Calculations
Question: How can you print the total sum of column 2 after reading an entire file?
* A) awk '{sum += $2} END {print sum}' file.txt
* B) awk 'BEGIN {sum += $2} {print sum}' file.txt
* C) awk '{print sum($2)}' file.txt
* D) awk 'END {sum += $2; print sum}' file.txt
Answer: A
Explanation: The main body {sum += $2} accumulates the sum for every line, and the END block runs once after reading the entire file to display the final result.
Question 9: Regular Expression Matching
Question: Which operator tests if field 1 contains the pattern error (case-sensitive)?
* A) $1 == /error/
* B) $1 ~ /error/
* C) $1 =~ /error/
* D) $1 matches "error"
Answer: B
Explanation: ~ is the regular expression match operator in awk. !~ tests for non-matching.
Question 10: Filtering Specific Line Ranges
Question: What does awk 'NR >= 5 && NR <= 10' file.txt do?
* A) Prints lines that have between 5 and 10 columns
* B) Prints lines 5 through 10 of the file
* C) Deletes lines 5 to 10
* D) Skips lines 5 through 10
Answer: B
Explanation: NR evaluates line numbers. Since no action {...} is provided, awk applies the default action: print the matching record.
Question 11: Emulating wc -l
Question: Which one-liner prints the total line count of a file, equivalent to wc -l?
* A) awk '{count++}' file.txt
* B) awk 'END {print NR}' file.txt
* C) awk 'BEGIN {print NR}' file.txt
* D) awk '{print NF}' file.txt
Answer: B
Explanation: At the end of processing, NR holds the total count of records processed.
Question 12: Column Value Filtering
Question: How do you print lines where the 3rd field is numeric and greater than 50?
* A) awk '$3 > 50 {print $0}' file.txt
* B) awk '{if ($3 > 50)}' file.txt
* C) awk 'WHERE $3 > 50' file.txt
* D) awk 'FILTER($3, 50)' file.txt
Answer: A
Explanation: Conditions outside braces act as pattern filters: $3 > 50 selects records where field 3 exceeds 50, triggering the {print $0} action (or default print).
Question 13: In-Place Substitution
Question: What does the built-in function sub(/foo/, "bar", $0) do?
* A) Replaces all occurrences of foo with bar in the line
* B) Replaces only the first occurrence of foo with bar in the line
* C) Splits $0 at every foo
* D) Reverses foo into bar across all files
Answer: B
Explanation: sub() replaces only the first match. To replace all occurrences globally, use gsub().
Question 14: String Length Calculation
Question: Which command outputs only records whose overall line length exceeds 80 characters?
* A) awk 'size($0) > 80' file.txt
* B) awk 'length($0) > 80' file.txt
* C) awk 'chars($0) > 80' file.txt
* D) awk 'strlen > 80' file.txt
Answer: B
Explanation: length() calculates the string length in characters (or defaults to $0 if no argument is passed).
Question 15: Removing Duplicate Consecutive/Non-consecutive Lines
Question: What classic idiom prints unique lines while preserving original order?
* A) awk '!seen[$0]++' file.txt
* B) awk 'unique($0)' file.txt
* C) awk 'distinct {print $0}' file.txt
* D) awk '{dedup($0)}' file.txt
Answer: A
Explanation: Associative array seen tracks lines. For the first occurrence of a line, seen[$0] evaluates to 0 (false), which ! flips to true, executing the default print action; the post-increment ++ sets it to 1, causing future occurrences to evaluate to false.
Question 16: Custom Record Separator
Question: By default, what is the Record Separator (RS) set to?
* A) Space
* B) Tab (\t)
* C) Newline (\n)
* D) Comma (,)
Answer: C
Explanation: RS defaults to a newline character (\n), meaning each line is treated as an independent record.
Question 17: String Splitting
Question: What does split("user@domain.com", arr, "@") produce?
* A) arr[0]="user", arr[1]="domain.com"
* B) arr[1]="user", arr[2]="domain.com"
* C) A syntax error because arrays cannot hold strings
* D) arr["@"]="user domain.com"
Answer: B
Explanation: In awk, array indexes created by functions like split() start at 1, not 0.
Question 18: Line Inversion / Pattern Inversion
Question: How do you print all lines that do not contain the word DEBUG?
* A) awk '!/DEBUG/' file.txt
* B) awk 'NOT /DEBUG/' file.txt
* C) awk '/^DEBUG/' file.txt
* D) awk 'drop(/DEBUG/)' file.txt
Answer: A
Explanation: The logical NOT operator ! negates pattern matches; !/pattern/ selects lines that do not match.
Question 19: External Shell Variables
Question: What is the recommended flag to pass an external bash/environment variable val="abc" into an awk variable x?
* A) awk -e x="$val" '{print x}' file.txt
* B) awk -v x="$val" '{print x}' file.txt
* C) awk --set x="$val" '{print x}' file.txt
* D) awk -var x="$val" '{print x}' file.txt
Answer: B
Explanation: The -v flag assigns a value to an awk variable before execution starts.
Question 20: Built-in printf Formatting
Question: What does awk '{printf "%-15s %5.2f\n", $1, $2}' data.txt do?
* A) Prints field 1 centered and field 2 in hexadecimal
* B) Left-aligns field 1 within 15 characters and formats field 2 as a floating point number with 2 decimal places
* C) Truncates field 1 to 15 chars and divides field 2 by 5.2
* D) Throws a syntax error because printf does not accept format specifiers in awk
Answer: B
Explanation: awk supports standard C-style printf formatting: %-15s means a left-justified string of width 15, and %5.2f specifies a float with minimum width 5 and 2 decimal points.
Quick Answer Key
| # | Answer | Key Topic |
|---|---|---|
| 1 | B | Field extraction & default IFS |
| 2 | B | $0 (current record) |
| 3 | C | $NF (dynamic last column) |
| 4 | B | -F delimiter option |
| 5 | B | NR vs FNR distinction |
| 6 | B | OFS (Output Field Separator) |
| 7 | B | BEGIN block lifecycle |
| 8 | A | END block summation |
| 9 | B | ~ regex matching operator |
| 10 | B | NR line range selection |
| 11 | B | END {print NR} line count |
| 12 | A | Numeric field condition |
| 13 | B | sub() vs gsub() |
| 14 | B | length() string function |
| 15 | A | !seen[$0]++ deduplication |
| 16 | C
| Default RS (\n) |
| 17 | B | 1-based indexing in split() |
| 18 | A | !/regex/ pattern negation |
| 19 | B | -v argument passing |
| 20 | B | printf string & float formatting |
No comments:
Post a Comment