Practice using awk to parse and transform structured
text quickly from the command line. Extract fields, apply
conditions, format custom output, and produce counts using
record-driven logic.
You are validating user account data and need fast, repeatable
text parsing without opening an editor. Your source is
/etc/passwd, and your job is to extract specific
fields, filter records by conditions, and format clean output
for review.
awk
is a standard tool for one-pass parsing and reporting. It is
especially useful when you need to confirm account state,
spot anomalies, or generate quick summaries during
troubleshooting.
/etc/passwd.
NR.
awk -F (colon-delimited
input).
{print $N}.
$3 == 0.
-v.
NR in an END
block.
awk -F: '{print $1}' /etc/passwd
-F:
sets the field separator to a colon, which matches the
structure of /etc/passwd. Printing
$1 extracts the username column only.
root
daemon
sys
...
awk -F: '$3 == 0 {print $0}' /etc/passwd
This filters the file based on a numeric condition. Printing
$0 outputs the entire matching line, which is
useful when you need the full record for evidence or review.
root:x:0:0:root:/root:/bin/bash
awk -F: -v sep=' -> ' '{print $1 sep $7}' /etc/passwd
# OR
awk -v sep=' -> ' -F: '{print $1 sep $7}' /etc/passwd
-v
defines an awk variable before processing begins. This lets
you standardize output formatting without hardcoding the
delimiter into multiple print statements.
root -> /bin/bash
daemon -> /usr/sbin/nologin
sys -> /usr/sbin/nologin
...
cat /etc/passwd | awk 'END{print NR}'
NR
is the current record number. In the
END
block, it represents the total count of records processed.
This is a quick way to count lines while using awk’s
execution model.
42
awk -F: '$7 == "/bin/bash" {print $1}' /etc/passwd
This checks the login shell field (field 7). Printing
$1 returns just usernames that match the
condition, which is a common audit pattern when you need to
quickly identify interactive accounts.
root
student
awk -F: '{print $1}' /etc/passwd
: Uses a colon field separator and prints the first field
(username).
-F:
: Sets the input field separator to :.
$1
: First field (username in /etc/passwd).
awk -F: '$3 == 0 {print $0}' /etc/passwd
: Filters records where UID equals 0 and prints the full
line.
$3
: Third field (UID in /etc/passwd).
$0
: Entire current record (the full line).
awk -F: -v sep=' -> ' '{print $1 sep $7}' /etc/passwd
: Formats output by printing username and shell with a custom
separator.
-v sep='...'
: Defines an awk variable used during processing.
$7
: Seventh field (login shell in /etc/passwd).
cat /etc/passwd | awk 'END{print NR}'
: Counts the number of records by printing NR in
the END block.
NR
: Record number (total records when used in
END).
END{...}
: Runs once after all input is processed.
awk -F: '$7 == "/bin/bash" {print $1}' /etc/passwd
: Prints usernames for accounts with a /bin/bash
login shell.
$7 == "/bin/bash"
: Condition matching the shell field.
{print $1}
: Outputs username only.