[sed] Replace just the last occurrence on each line

Created on November 30, 2026

Capture as much text as possible before the target to make sed choose the last match on the line.

printf 'foo foo foo\n' | sed 's/\(.*\)foo/\1bar/'
foo foo bar

.* is greedy, so the capture group contains everything before the last foo. The replacement \1bar restores that prefix and adds bar.

Bash Shell command sed