Typorithm · hard

sed & awk

bash-sed-awkbashsedawkfields
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn sed & awk

0%

Text Processing

sed is a stream editor: s/old/new/g substitutes all matches per line, and -n with p prints only selected lines or ranges. awk processes records by field — $1 is the first field, -F sets the delimiter, and a pattern like $3 > 100 guards the action.

sed edits a text stream line by line. Its workhorse is substitution: sed 's/foo/bar/g' file.txt replaces every foo with bar, where the trailing g makes the change global instead of first-match-only.

By default sed prints every line. Pairing -n (suppress output) with the p command prints only what you ask for, so sed -n '1,5p' file.txt emits just lines 1 through 5.

awk reads each line as a record split into fields. $1, $2, ... reference fields, -F sets the delimiter (here a comma for CSV), and a leading pattern such as $3 > 100 guards the { } action so it runs only on matching records.

01

sed s/old/new/g substitutes every match on a line.

02

sed -n '1,5p' prints only the selected line range.

03

awk fields are $1, $2, ...; -F sets the delimiter; a pattern guards the action.

sed 's/foo/bar/g' file.txt
sed -n '1,5p' file.txt
awk '{print $1}' access.log
awk -F, '{print $2}' data.csv
awk '$3 > 100 {print $1}' data.txt

Read the implementation

Connect each part of the code to the concept before you type.

1. Substitute all

s/foo/bar/g replaces every occurrence of foo with bar on each line; the trailing g makes it global.

sed 's/foo/bar/g' file.txt

2. Print a range

-n suppresses the default output and p prints only lines 1 through 5.

sed -n '1,5p' file.txt

3. First field

awk splits each line into fields; $1 is the first field, printed for every record.

awk '{print $1}' access.log

4. Custom delimiter

-F, sets the field separator to a comma, so $2 is the second CSV column.

awk -F, '{print $2}' data.csv

5. Pattern guard

The pattern $3 > 100 runs the action only on records whose third field exceeds 100.

awk '$3 > 100 {print $1}' data.txt

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

sed & awk: Lesson & Practice · Typorithm | ApplyDjinn