Using `sed` to find and replace in file
sed = Stream EDitor

sed find and replace text

1
sed 's/word1/word2/g' input.file
Copied!
Find and replace text and save to new file
1
sed 's/word1/word2/g' input.file > output.file
Copied!
Note:
  • s/ means substitute
  • /g means global replace

Can change delimiter / to something else:

1
sed 's~word1~word2~g' input.file > output.file
Copied!

Find and replace in the line contains something

1
sed -i -e '/FOO/s/love/sick/' input.txt
Copied!
In this example only find the word love and replace it with the sick if line content a specific string such as FOO

Find and replace multiple files in sub-folder

1
find ./ -type f -exec sed -i -e 's/apple/orange/g' {} \;
Copied!
-i to save the temporary file
Last modified 5mo ago