SkillSprout
Chapter 1 · Lesson 10
Intermediate
1 min read

Process Data with sort, cut, wc and awk

Overview

Text-processing commands read rows or fields and produce a transformed stream. Combining them creates repeatable reports without writing a full program.

Detailed Notes

Count lines, words and bytes

bash
wc -l app.log
wc -w app.log
wc -c app.log

-l counts newline characters, -w counts whitespace-separated words and -c counts bytes.

Sort and remove adjacent duplicates

bash
sort access.log
sort -rn scores.txt
sort names.txt | uniq -c

uniq removes only adjacent duplicates, so sort the input first.

Select columns

bash
cut -d ':' -f1 /etc/passwd
awk -F ':' '{print $1, $7}' /etc/passwd
  • -d ':' sets the delimiter.
  • -f1 selects field 1.
  • awk splits each row into fields, then executes a block.

$1 is the first field and $7 is the seventh field.

Aggregate with awk

bash
awk '{count[$1]++} END {for (name in count) print name, count[name]}' access.log

This creates an associative array keyed by the first field, increments each key and prints totals at the end.

Practice

Create:

bash
printf 'alice 10
bob 20
alice 15
' > scores.txt

Read the file and produce a total for each name.

Common Interview Questions

Finished this lesson?

0 of 25 lessons done · 0% of the course