Home > Operation and Maintenance > Linux Operation and Maintenance > How to batch replace file contents in Linux

How to batch replace file contents in Linux

WBOY
Release: 2022-03-23 09:24:04
Original
20376 people have browsed it

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`".

How to batch replace file contents in Linux

#The operating environment of this tutorial: linux7.3 system, Dell G3 computer.

How to batch replace file contents in Linux

Method 1

Use perl, the command is as follows:

find -name '要查找的文件名' | xargs perl -pi -e 's|被替换的字符串|替换后的字符串|g'
Copy after login

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'
Copy after login

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'
Copy after login

Method 2

Use the sed command as follows:

sed -i "s/原字符串/新字符串/g" `grep 原字符串 -rl 所在目录`
Copy after login

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'
Copy after login

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`
Copy after login

Example code:

sed -i "s/大小多少/日月水火/g" `grep 大小多少 -rl /usr/aa`
sed -i "s/大小多少/日月水火/g" `grep 大小多少 -rl ./`
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template