Skip to content
Visual explainer 4h to learn 5 steps

Text processing: grep, sed, awk, sort, cut

Extract and transform information from logs and config files with one-liners.

By Invicly Tech, , in Linux Administration (RHCSA-style). About 10 minutes to read.

Topic 3 of 42

In short

Most administration is reading text: logs, config files and command output. grep finds lines, sed edits them, awk and cut pull out columns, and sort and uniq summarise. Chained with pipes they answer questions like which IPs failed SSH logins most often in seconds.

Explained simply

On Linux, almost everything is text: config files, logs, and the output of most commands. So a big part of an admin's job is reading text and pulling out the bit that matters. A few small tools do this very well, and each does one job.

grep finds lines that contain a pattern. sed changes text as it flows past, for example replacing one word with another. awk and cut pick out columns, like the third word on each line. sort puts lines in order, uniq removes or counts repeats, and diff shows what changed between two files.

The real power comes from joining them with the pipe symbol |, which passes one tool's output to the next tool. Each step is simple, but together they answer real questions, such as which user runs the most processes or which page returns the most errors.

Patterns are written as regular expressions, a small language for describing text. ^ means start of line, $ means end of line, . means any character and * means repeat the thing before it. You only need a few of these to be productive.

Press Play on a diagram to walk through it one step at a time.

FlowFrom a log file to an answer
  1. 1
    grep

    Keep lines matching Failed password.

  2. 2
    awk

    Print the field holding the IP address.

  3. 3
    sort

    Group identical IPs together.

  4. 4
    uniq -c

    Count each IP.

  5. 5
    sort -rn | head

    Show the top offenders.

CompareWhich tool for which job
grep
  • Find lines
  • Filter in or out
  • Count matching lines
  • Search whole directories
sed
  • Replace text
  • Delete lines by pattern
  • Edit files in place with -i
  • Print a range of lines
awk
  • Pick columns
  • Filter by a field's value
  • Sum and average
  • Format a small report

In depth

Regular expressions and grep flags that matter

grep uses basic regular expressions by default. In that mode, characters like + ? | ( and { have no special meaning unless you put a backslash before them. grep -E switches to extended regular expressions, where they work directly: grep -E 'error|fail' finds either word. grep -F treats the pattern as plain text, which is fastest and avoids surprises with dots in IP addresses.

Useful flags: -n shows line numbers, -c counts matching lines (not matches), -o prints only the matched part, -w matches whole words, -l lists only file names, and -A 3, -B 3 or -C 3 show lines after, before or around each hit. grep -q prints nothing and only sets the exit status: 0 if something matched, 1 if nothing did, 2 on an error. Scripts use that in if statements.

  • [[:digit:]] and [0-9] both match one digit
  • ^$ matches an empty line
  • grep -v '^#' drops comment lines
  • grep -rn 'Listen' /etc/httpd searches a whole tree

How sed processes a stream

sed reads one line at a time into a buffer called the pattern space, runs your commands on it, prints it, and moves on. The most common command is s/old/new/flags. The g flag replaces every match on the line, not just the first. In the replacement, & stands for the whole matched text. You can pick another delimiter when the text has slashes: s|/usr/local|/opt| is easier to read.

Commands can have an address that limits where they run: a line number (3d deletes line 3), a pattern (/^#/d deletes comment lines) or a range (10,20s/a/b/). sed -n stops the automatic printing, so sed -n '/ERROR/p' acts like grep. sed -i changes the file in place; sed -i.bak does the same but keeps a backup copy first.

CycleThe sed loop for every line
  1. 1
    Read a line

    Copy it into the pattern space

  2. 2
    Check the address

    Does this line match the line number or pattern?

  3. 3
    Run commands

    s, d, p and so on change the buffer

  4. 4
    Print the buffer

    Skipped with -n or after d

  5. Back to step 1

awk for columns, filters and totals

awk splits each line into fields. $1 is the first field, $NF the last, and $0 the whole line. By default fields are separated by any run of spaces or tabs, which is why awk handles command output like ps or df far better than cut. -F sets another separator, such as -F: for /etc/passwd.

An awk program is a list of pattern { action } pairs. The pattern filters lines: awk -F: '$3 >= 1000 {print $1}' /etc/passwd prints normal user names. NR is the current line number and NF the number of fields. BEGIN runs before the first line and END after the last, so totals are easy: awk '{sum += $5} END {print sum}' adds up column 5.

cut is simpler and faster but only takes a single-character delimiter and treats two spaces as an empty field between them.

  • awk 'NR==1' prints only the first line
  • awk '{print $1, $NF}' prints the first and last fields
  • cut -c1-10 cuts by character position
  • printf in awk formats aligned output

sort, uniq and diff in detail

sort compares text by default, so 10 comes before 9. Use -n for numbers, -h for human sizes like 4K, 2M and 1G (perfect after du -h), -r to reverse and -k to choose a column: sort -t: -k3,3n sorts /etc/passwd by UID. sort -u removes duplicate lines in one step.

uniq only merges neighbouring identical lines, so it almost always follows sort. uniq -c counts each group, uniq -d shows only repeated lines and uniq -u only unique ones.

diff compares two files. With -u it prints the unified format used by patches and code review: lines starting with - were removed, + were added, and @@ markers show where. diff -r compares whole directories, which is a quick way to see what changed between a config backup and the live /etc.

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Search with grep and regular expressions~50m
  2. 2
    Edit streams with sed substitutions~50m
  3. 3
    Print columns with awk and cut~50m
  4. 4
    Count and deduplicate with sort and uniq~50m
  5. 5
    Compare files with diff~50m

Key points

  • grep -i ignores case, -v inverts, -r recurses and -E enables extended regex.
  • sed -i edits a file in place; test without -i first.
  • awk splits lines into fields $1, $2 and so on; -F sets the separator.
  • uniq only collapses adjacent duplicates, so sort first.

Key terms

Tap a card to flip it. 0/5 known

Examples

bash
grep -E "^[^#]" /etc/ssh/sshd_config            # non-comment lines
sudo journalctl -u sshd | grep "Failed password" \
  | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head
cut -d: -f1,7 /etc/passwd                       # user and shell
sed 's/^PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config | grep PermitRoot

Real admin one-liners; preview sed changes before using -i.

Summarise a web server access log

In the common combined log format, field 1 is the client IP, field 7 the requested path and field 9 the HTTP status code. Step 1: count requests per status code. Step 2: list the five IPs that sent the most requests. Step 3: show which paths produced server errors (status 5xx), most frequent first. Each line is just a filter, a column picker and a count.

bash
LOG=/var/log/nginx/access.log
awk '{print $9}' "$LOG" | sort | uniq -c | sort -rn
awk '{print $1}' "$LOG" | sort | uniq -c | sort -rn | head -5
awk '$9 ~ /^5/ {print $7}' "$LOG" | sort | uniq -c | sort -rn | head

Change a config value safely with sed

You must turn off SSH password logins. The line may be commented out or set to yes. Step 1: see what is there now with grep -n. Step 2: preview the change by running sed without -i and filtering the result. Step 3: apply it with -i.bak so a backup exists. Step 4: diff the backup and the new file. Step 5: let sshd check the syntax before you reload it. On cloud images also check /etc/ssh/sshd_config.d/, because sshd uses the first value it reads for most settings.

bash
F=/etc/ssh/sshd_config
grep -n 'PasswordAuthentication' "$F"
sed -E 's/^#?PasswordAuthentication .*/PasswordAuthentication no/' "$F" | grep -n '^PasswordAuth'
sudo sed -i.bak -E 's/^#?PasswordAuthentication .*/PasswordAuthentication no/' "$F"
diff -u "$F.bak" "$F"
sudo sshd -t && sudo systemctl reload sshd

Quick reference

  • grep -E 'a|b' matches either word; grep -F 'x.y' matches the dot literally
  • grep -c counts matching lines, not total matches; grep -o word | wc -l counts matches
  • grep -C 3 pattern file shows 3 lines of context around each match
  • sed -n '10,20p' file prints only lines 10 to 20
  • sed -i.bak 's/old/new/g' file edits in place and keeps file.bak
  • awk -F: '$3 >= 1000 {print $1}' /etc/passwd lists normal user accounts
  • du -sh * | sort -h sorts human-readable sizes correctly
  • diff -u old new shows changes with - for removed and + for added lines

Common mistakes

  • Running sed -i on a config file without a backup or a dry run.
  • Forgetting to quote patterns so the shell expands them first.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A log line contains the word error three times. What does grep -c error print for a file with only that line?

Question 2

2Which command prints the user name and UID columns of /etc/passwd?

Question 3

3What does & mean in the sed command s/[0-9]+/[&]/ with -E?

Question 4

4Why does sort put 100 before 9 by default?

Question 5

5Which flag makes grep print nothing and only report success or failure through its exit status?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Show all lines in /etc/ssh/sshd_config that are not comments and not empty.

  2. Exercise 2medium

    List every login shell used in /etc/passwd with the number of accounts using it, most common first.

  3. Exercise 3hard

    Using ps output, print the total memory (RSS, in MB) used by each user, largest first, as a neat two-column report.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between grep, egrep and grep -E?
egrep is an old name for grep -E. Recent GNU grep prints a warning when you use egrep, so write grep -E in new scripts.
Should I use awk or cut?
Use cut for files with a single, consistent delimiter like /etc/passwd. Use awk for command output with variable spacing or when you need conditions or totals.
How do I undo sed -i?
You cannot, unless you kept a backup. Use sed -i.bak, or preview the result without -i first and compare with diff.
Why does my grep pattern with a dot match too much?
In a regular expression a dot means any character, so 10.0.0.1 also matches 10a0b0c1. Escape the dots or use grep -F for fixed text.

Go deeper

ShareXLinkedInWhatsApp