[sed] Replace text on a specific line

Created on November 30, 2026

Put a line number before the substitution command to restrict it to that line. Here, 3 addresses the third line and s/foo/bar/ replaces foo with bar on that line.

printf 'foo\nfoo\nfoo\n' | sed '3s/foo/bar/'
foo
foo
bar

To address a range such as lines 2 through 4, use 2,4s/foo/bar/.

Bash Shell command sed