Method: 1. Use the perl command, the syntax is "find -name'file name'|xargs perl-pi-e 's|Original content|New content|g'"; 2. Use the sed command, The syntax is "sed-i "s/original content/new content/g" `grep original content-rl directory`".
#The operating environment of this tutorial: linux7.3 system, Dell G3 computer.
Method 1
Use perl, the command is as follows:
find -name '要查找的文件名' | xargs perl -pi -e 's|被替换的字符串|替换后的字符串|g'
The following example is to Replace ”http://repo1.maven.org/maven2“ in all pom.xml files in the current directory and all subdirectories with ”http://localhost:8081/nexus/content /groups/public“.
find -name 'pom.xml' | xargs perl -pi -e 's|http://repo1.maven.org/maven2|http://localhost:8081/nexus/content /groups/public|g'
The Perl language is used here,
perl -pi -e Add the -e option to the Perl command, followed by a line of code, then it will Run this code like a normal Perl script.
Using Perl from the command line can help achieve some powerful, real-time transformations. Studying regular expressions carefully and using them correctly will save you a lot of manual editing work.
find -name 'pom.xml' | xargs perl -pi -e 's|http://repo1.maven.org/maven2|http://localhost:8081/nexus/content/groups/public|g'
Method 2
Use the sed command as follows:
sed -i "s/原字符串/新字符串/g" `grep 原字符串 -rl 所在目录`
A simple method to batch replace strings in multiple files under Linux. Use the sed command to batch replace strings in multiple files.
For example: I want to replace mahuinan with huinanma, execute the command:
sed -i "s/mahuinan/huinanma/g" 'grep mahuinan -rl /www'
This is currently the simplest batch replacement string command in Linux!
The specific format is as follows:
sed -i "s/oldString/newString/g" `grep oldString -rl /path`
Example code:
sed -i "s/大小多少/日月水火/g" `grep 大小多少 -rl /usr/aa` sed -i "s/大小多少/日月水火/g" `grep 大小多少 -rl ./`
Related recommendations: "Linux Video Tutorial"
The above is the detailed content of How to batch replace file contents in Linux. For more information, please follow other related articles on the PHP Chinese website!