简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM