Various methods of batch replacing files under Linux (transfer)

 

   Reprinted from: http://www.2cto.com/os/201212/172658.html

Various methods of batch replacing files under Linux
 
1: Find www.2cto.com  
find . -type f -name "*.html"|xargs grep ‘yourstring’
 
2: Find and replace
find -name 'file name to find' | xargs perl -pi -e 's|replaced string|replaced string|g'
 
perl -pi -e
Add the -e option to a Perl command, followed by a line of code, and it will run the code like a normal Perl script.
 
Using Perl from the command line can help with some powerful, real-time transformations. Studying regular expressions carefully, and using them correctly, will save you a lot of manual editing.
 
3: Batch modify folder permissions
 
find . -type -d -name *.html|xargs chmod 755
 
4: Batch modify file permissions
 
find . -type -f -name *.html|xargs chmod 644
 
Find and replace are very common operations.
 
The little tricks described here can make it easy for you to complete a lot of repetitive and tedious work.
 
Illustrate with an example
 
Find the string "password" in a .c file in the current directory
grep "password" *.c
 
Find the file test.c in the current directory and its multiple subdirectories
find . -name "test.c" -print
 
Find and delete .vbs files in the current directory and its multiple subdirectories
find . -name "*.vbs" -exec rm {} \;
 
Find the string "password" in .c files in the current directory and its multiple subdirectories
find . -name "*.c" -print | xargs grep "password"
 
Replace the string "password" with "pwd" in the .c file in the current directory
perl -pi -e 's/password/pwd/g' *.c
 
Replace the string "password" with "pwd" in the .c file in the current directory and back it up with a .bak extension
perl -pi.bak -e 's/password/pwd/g' *.c
 
Replace the string "password" with "pwd" in the .c files in the current directory and subdirectories
find . -name "*.c" -print | xargs perl -pi -e 's/password/pwd/g'
 
Batch replace with sed operation
 
  Format: sed -i "s/find field/replace field/g" `grep find field -rl path`
 
  linux sed batch replace strings in multiple files
 
  sed -i "s/oldstring/newstring/g" `grep oldstring -rl yourdir`
 
  For example: replace www.csdn.net in all files under /home with www.iteye.com
 
  sed -i "s/www. csdn. net/www. iteye.com /g" `grep www. csdn . net -rl /mysites`
 
   Operate in the current directory: sed -i "s/www.csdn.net/www.iteye.com /g" *

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326360427&siteId=291194637