乐闻世界logo
搜索文章和话题

How to replace a string in multiple files in linux command line

1个答案

1

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:

bash
sed -i 's/old_string/new_string/g' filename
  • -i option indicates direct modification of the file content.
  • s represents the replacement operation.
  • /old_string/new_string/ is the replacement pattern, where g denotes 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:

bash
find . -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:

bash
find . -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:

bash
sed -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!

2024年7月11日 10:01 回复

你的答案