Search for and replace a string in all files in a directory in centos

Source: Internet
Author: User
Tags centos


For some reason, a method in the project is lost, and many files reference this method. You need to replace all of them with a new method. This method is referenced many times and manual modification is too troublesome. therefore, one-time replacement is required.

For example, to change the old in all files under the dir directory to new:

Sed-I "s/old/new/g" 'grep' old '-rl dir'

1. Find the file containing a string in the directory.

For example, find all files containing str in the dir directory.


Grep-lr 'str' dir

2. vim replaces all strings in a single file

For example, replace all old objects in the current file with new


: % S/old/new/g

3. Replace a string from all files in the directory-sed with grep

For example, you need to change the old values in all files under the dir directory to new:


Sed-I "s/old/new/g" 'grep' old '-rl dir'

4. A simple method to replace strings in multiple files in batches.

You can use the sed command to replace strings in multiple files in batches.
               
Sed-I "s/original string/new string/g" 'grep original string-rl Directory'
For example, I want to replace mahuinan with huinanma,

 

Run the following command: sed-I "s/mahuinan/huinanma/g" 'grep mahuinan-rl/www'

This is the simplest string replacement command in linux!
The specific format is as follows:

Sed-I "s/oldString/newString/g" 'grep oldString-rl/path'

Instance code: sed-I "s/size/Sun/month/g" 'grep size-rl/usr/'
Sed-I "s/size/Sun/month/g" 'grep size-rl ./'
Note that escape is required:

Instance:


Sed-I "s/<script src = \" http: \/ajax.googleapis.com \/ajax \/libs \/jquery \/1.4 \/

Query. min. js \ "type = \" text \/javascript \ "> <\/script> // g"

'Grep' <script src = "http: \ // ajax.googleapis.com \/ajax \/libs \/jquery \/1.4 \/

Jquery. min. js "type =" text \/javascript "> <\/script> '-rl test /'
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.