Skip to content
shellhacks.dev
Text Processing

Replace Only the Nth Match on a Line with sed

Replace only the second or a later match on a line with a numeric flag on the s command, and add g to replace from that match onward. The count restarts on every line.

1 min read
Summarize in AI

A line contains the same word several times and only one specific occurrence should change.

Shell
echo 'a-a-a-a' | sed 's/a/X/2'
echo 'a-a-a-a' | sed 's/a/X/2g'
echo 'a-a-a-a' | sed 's/a/X/9'
printf 'a a\na a\n' | sed 's/a/X/2'
Text
a-X-a-a
a-X-X-X
a-a-a-a
a X
a X

A number after the replacement picks the Nth match on each line, so s/a/X/2 changed only the second a in a-a-a-a. Adding g after the number means that match and every one after it, which gave a-X-X-X. A number higher than the match count leaves the line unchanged, and the count starts again on each line, as the two-line input shows. See The s Command in the manual.

The count is per line. To count across a whole file, join the lines first with sed -z in GNU sed, or use awk. Combining a number with g is standard, but old sed versions on some Unix systems reject the combination.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.