Kender
Kender

Reputation: 1254

Mass Find/Replace within files having specific filename under command line

I am looking for a quick command to search all .htaccess files for a specific IP address and change it to another IP address from the command line

something like

grep -rl '255.255.254.254' ./ | xargs sed -i 's/254/253/g'

I know the above example is a bad way to do it, just an example (and showing I did some searching to find a solution

Search: files with filename .htaccess (within 2 levels deep of current path?)
Find: 255.255.254.254
Replace with: 255.255.253.253

or, is this too much to ask of my server and I would be better off replacing them as I find them?

Upvotes: 1

Views: 20

Answers (1)

John1024
John1024

Reputation: 113814

Try:

find . -type f -name '.htaccess' -execdir sed -i 's/255\.255\.254\.254/255.255.253.253/g' {} +

How it works:

  • find .

    Start looking for files in the current directory.

  • -type f

    Look only for regular files.

  • -name '.htaccess'

    Look only for files named .htaccess.

  • -execdir sed -i 's/255\.255\.254\.254/255.255.253.253/g' {} +

    For any such files found, run this sed command on them.

    Because . is a wildcard and you likely want to match only literal periods, we escape them: \.

    We use -execdir rather than the older -exec because it is more secure against race conditions.

Upvotes: 1

Related Questions