Много рецептов есть здесь: https://unix.stackexchange.com/questions/112023/how-can-i-replace-a-string-in-a-files

Часто используемые рецепты:

 

  • Replace foo with bar only if there is a baz later on the same line:

    sed -i 's/foo\(.*baz\)/bar\1/' file

    In sed, using \( \) saves whatever is in the parentheses and you can then access it with \1. There are many variations of this theme, to learn more about such regular expressions, see here.