Replacing strings across multiple files in the Linux command line is a common and powerful task, with sed (stream editor) being a very useful tool. Below, I will explain how to use this tool and provide a specific example.
Using sed Command
sed is a stream editor capable of powerful text transformations. It can not only replace text but also perform insertions, deletions, and other text editing operations. For replacing strings across multiple files, we typically combine sed with the find or grep commands.
Command Format
The basic sed command format for string replacement is as follows:
bashsed -i 's/old_string/new_string/g' filename
-ioption indicates direct modification of the file content.srepresents the replacement operation./old_string/new_string/is the replacement pattern, wheregdenotes global replacement, meaning all matches on each line are replaced.
Replacing Multiple Files
To replace strings across multiple files, you can combine find or xargs with sed:
bashfind . -type f -name "*.txt" -exec sed -i 's/old_string/new_string/g' {} +
This command searches for all files with the .txt extension in the current directory and its subdirectories, replacing the strings within them.
Specific Example
Suppose we have a project directory containing multiple .log files, and we need to replace the error marker ERROR with WARNING in these log files.
We can achieve this with the following command:
bashfind . -type f -name "*.log" -exec sed -i 's/ERROR/WARNING/g' {} +
This command traverses the current directory and all subdirectories, locating all .log files and replacing ERROR with WARNING.
Important Notes
When using sed -i for replacement, be sure to back up the original file to prevent errors. You can create a backup file using -i.bak:
bashsed -i.bak 's/old_string/new_string/g' filename
This saves the original file as filename.bak.
This is how to replace strings across multiple files in the Linux command line. I hope this helps you!