How Do You Replace a Pattern with a String in Bash?

Problem scenario
You have a .txt file. You know Linux can support substitutions of strings with some type of expression. You want to use Bash to replace every occurrence in the file with a string. What should you do?

Let's assume the file you have is called coolfile.txt. Run these two commands to replace "foo" with "bar" every time "foo" is found in the file named coolfile.txt:

oldfile=$(cat coolfile.txt)
echo "${oldfile//'foo'/bar}" > newfile.txt
# The resulting file newfile.txt will have "bar" instead of "foo"

Leave a comment

Your email address will not be published. Required fields are marked *