Search/replace commands
Find and Replace String in Files
If you just need to perform a simple search and replace, you can use the following syntax:
sed -i 's/string_to_find/string_to_replace/' file1 file2 fileN
Here:
-i
: This flag indicates to sed that your input file is expected to be one of the files specified after the command.
string_to_find
: This is the string that you want to search for in the files.
string_to_replace
: This is the string that you want to replace the string what_to_find within the files.
file1 file2 fileN
: This is the list of files that sed will search and replace.
The following command will search for all strings “Hello” in the welcome.txt file. Then replace it with a new string “Howdy” in the same file.
sed -i 's/Hello/Howdy/g' welcome.txt
You can also create a backup of original file before making changes with -i followed by some extension. For example:
sed -i.backup 's/Hello/Howdy/g' welcome.txt
This will create a file welcome.txt.backup
in the current directory with the original file content.