What if you want to replace text in a file? Use sed. I will give the simplest example. First, I’m creating a text file that has “hello world” in it.
echo 'hello world' > test.txt
I’m going to replace “hello” with “hi” and create a new file called test_new.txt.
cat test.txt | sed 's/hello/hi/g' > test_new.txt
You can accomplish the same operation without using pipe.
sed 's/hello/hi/g' test.txt > test_new.txt
If you want to just replace the text without creating a new file…
sed -i 's/hello/hi/g' test.txt
If you want to create a backup file, you can add .bak right after -i option like the following example.
sed -i.bak 's/hello/hi/g' test.txt
This way, the original content of test.txt is preserved in test.txt.bak.