🎓 A1Learner
🔍
0 of 46 lessons completed

Bash Sed Substitution

Sed substitution is the act of replacing matched text with new text on chosen lines. The s command names the pattern, the replacement, and the flags that change how the match is replaced.

Backreferences swap captured parts

The pattern captures the name and the number as two groups. The replacement prints group 2 first and group 1 second, so each line swaps its two parts.

printf 'john-42\nmary-17\n' > users.txt
sed -E 's/([a-z]+)-([0-9]+)/\2-\1/' users.txt

Ampersand repeats the whole match

The pattern matches each number, and & in the replacement stands for that number. Each number reappears wrapped in square brackets.

printf 'price 50\nprice 120\n' > prices.txt
sed -E 's/[0-9]+/[&]/' prices.txt

The g and i flags change the reach

With g alone, every small-letter apple on a line changes, but Apple and APPLE stay. With gi, every case form changes too.

printf 'apple Apple APPLE\nbanana apple\n' > fruit.txt
sed 's/apple/orange/g' fruit.txt
sed 's/apple/orange/gi' fruit.txt

A different delimiter avoids slash escapes

The text holds slashes, so the command uses # as its delimiter instead of /. The first path changes its home folder, and the second path has no match, so it stays the same.

printf 'path /home/user/docs\npath /var/log\n' > paths.txt
sed 's#/home/user#/home/guest#' paths.txt

Example

printf 'john 42\nmary 17\n' > scores.txt
sed -E 's/([a-z]+) ([0-9]+)/\1 scored \2 points (raw: &)/' scores.txt

Key points

  • s command: s/pattern/replacement/ swaps matched text for new text.
  • Backreference: \1 in the replacement repeats the first captured group.
  • Ampersand: & in the replacement repeats the whole match.
  • g flag: replaces every match on a line, not just the first.
  • i flag: ignores letter case when matching.
  • Alternate delimiter: s#...# works like s/.../ when the text holds slashes.

In this example, the script first creates a small score list. The pattern captures the name as group 1 and the score as group 2. The replacement rebuilds each line with the name and score in words, and & adds the original pair in parentheses at the end.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

In sed, what does & mean in the replacement?