nube
nube

Reputation: 43

Bash script to find files based on filename and do search replace on them

I have a bunch of files (with same name, say abc.txt) strewn all over the network filesystem.

I need to recursively search for each of those files and once I find each one, do a content search and replace on them.

After some research, I see that I can find the files using the find command (with -r to recurse right?). Something like:

    find . -r -type f  abc.txt

And use sed to do find and replace on each one:

    sed -ie 's/search/replace/g' abc.txt

But I'm not sure how to glue the two together so that I find all occurrences of abc.txt and then do a search/replace on each one.

My directory tree is really large so I know a recursive search through all the directories will take a long time but that's better than manually trying to find each file.

I'm on OSX 10.6 with Bash.

Thanks all!

Update: I think the answer posted below may work for other OSes (linux perhaps) but for OSX, I had to tweak it a bit.

    find . -name abc.text -exec sed -i '' 's/search/replace/g' {} +

the empty quotes seem to required after a -i in sed to indicate that we don't want to produce a backup file. The man page for this reads:

-i extension:

Edit files in-place, saving backups with the specified extension. If a zero-length extension is given, no backup will be saved.

Upvotes: 2

Views: 1503

Answers (1)

amit_g
amit_g

Reputation: 31270

find . -r -type f abc.txt -exec sed -i -e 's/search/replace/g' {} +

Upvotes: 6

Related Questions