How can I replace text after a specific word using sed?

Search for a line that starts with projdir, and replace the whole line with a new one:

sed -i 's/^projdir .*$/projdir PacMan/' .ignore

^ and $ are beginning/end-of-line markers, so the pattern will match the whole line; .* matches anything. The -i tells sed to write the changes directly to .ignore, instead of just outputting them


One approach is to rewrite the entire line, using backreferences for the parts you want to keep:

sed -e 's/^\( *projdir  *\)[^ ]*\(.*\)*$/\1PacMan\2/'

Another approach is to rewrite that part of the line, but only if some other part matches:

sed -e '/^ *projdir / s/ [^# ]/ PacMan/'

Both examples rewrite the second whitespace-delimited word on lines where the first word is projdir.


Although this is an old post and it seems to be solved for you by the accepted answer, the actual question has not been answered. So for completeness and to help others:

Here the answer that actually matches for "Snake" and not for lines startting with "projdir"...

sed -r 's/(^.*)Snake/\1PacMan' .ignore

This replaces everything from the start of the line including "Snake" with everything before "Snake" + "PacMan". \1 stands for what is matched inside (). Everything after "Snake" remains untouched.