Find and Replace Inside a Text File from a Bash Command Find and Replace Inside a Text File from a Bash Command bash bash

Find and Replace Inside a Text File from a Bash Command


The easiest way is to use sed (or perl):

sed -i -e 's/abc/XYZ/g' /tmp/file.txt

Which will invoke sed to do an in-place edit due to the -i option. This can be called from bash.

If you really really want to use just bash, then the following can work:

while read a; do    echo ${a//abc/XYZ}done < /tmp/file.txt > /tmp/file.txt.tmv /tmp/file.txt{.t,}

This loops over each line, doing a substitution, and writing to a temporary file (don't want to clobber the input). The move at the end just moves temporary to the original name.

For Mac users:

sed -i '' 's/abc/XYZ/g' /tmp/file.txt (See the comment below why)


File manipulation isn't normally done by Bash, but by programs invoked by Bash, e.g.:

perl -pi -e 's/abc/XYZ/g' /tmp/file.txt

The -i flag tells it to do an in-place replacement.

See man perlrun for more details, including how to take a backup of the original file.


I was surprised when I stumbled over this...

There is a replace command which ships with the "mysql-server" package, so if you have installed it try it out:

# replace string abc to XYZ in filesreplace "abc" "XYZ" -- file.txt file2.txt file3.txt# or pipe an echo to replaceecho "abcdef" |replace "abc" "XYZ"

See man replace for more on this.