You can only do this with a shell. This example uses an unnecessary case statement for this particular example, but I turned it on to show how you can enable multiple replacements. Although the code is larger than sed 1-liner, it is usually much faster because it uses only built-in shells (up to 20x for small files).
REPLACEOLD="old" WITHNEW="new" FILE="tmpfile" OUTPUT="" while read LINE || [ "$LINE" ]; do case "$LINE" in *${REPLACEOLD}*)OUTPUT="${OUTPUT}${LINE//$REPLACEOLD/$WITHNEW} ";; *)OUTPUT="${OUTPUT}${LINE} ";; esac done < "${FILE}" printf "${OUTPUT}" > "${FILE}"
for a simple case, you can omit the case statement:
while read LINE || [ "$LINE" ]; do OUTPUT="${OUTPUT}${LINE//$REPLACEOLD/$WITHNEW} "; done < "${FILE}" printf "${OUTPUT}" > "${FILE}"
Note: ... || ["$ LINE"] ... a bit should prevent the loss of the last line of a file that does not end with a new line (now you know at least one question why your text editor continues to add them)
source share