Interview Q&A / Linux & Shell

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you print specific columns of a command's output with awk?

SHORT ANSWER

awk splits each line into fields on whitespace and gives them as $1, $2 and so on, with $NF as the last and $0 as the whole line. awk '{print $1, $3}' prints columns 1 and 3. Use -F to set another separator, such as -F: for /etc/passwd.

Explain it simply

awk reads text line by line and treats each line like a row in a spreadsheet. $1 is column 1, $2 is column 2, and so on.

ls -l | awk '{print $9, $5}' prints file name and size. $NF is the last column and $(NF-1) the one before it. NR is the line number.

The default separator is any run of spaces or tabs. For other formats use -F: awk -F: '{print $1}' /etc/passwd prints all user names, and -F, handles simple CSV.

awk can also filter with a condition before the action: awk '$3 > 100 {print $1}' data prints column 1 only for rows where column 3 is above 100. And it can do arithmetic: awk '{s+=$2} END {print s}' sums a column.

Quote the program in single quotes so the shell does not treat $1 as its own variable.

Example

bash
printf 'amit 80\nria 95\nkabir 70\n' | awk '{s+=$2} END {print s}'
# 245
awk -F: '{print $1, $7}' /etc/passwd | head -2
# root /bin/bash
# daemon /usr/sbin/nologin

What to say in the interview

"awk splits lines into fields, $1 to $NF, and runs a pattern-action program. I use it to pull columns, filter by a condition, or sum a column, and set the separator with -F. Programs go in single quotes."

Common mistakes

  • Using double quotes so the shell expands $1 before awk sees it.

#linux#text-processing#awk

Related questions

Practise more Linux & Shell questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Linux & Shell quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.