DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

One-line Shell Script For Find And Replace

04.10.2005
| 139816 views |
  • submit to reddit
        An equivalent of the other find-replace, except it's a one-liner that generates no temp files, and is more flexible:

perl -pi -e 's/find/replace/g' *.txt

Or, to change matching files in a hierarchy:

find . -name '*.txt' |xargs perl -pi -e 's/find/replace/g'
    

Comments

Snippets Manager replied on Sun, 2010/03/21 - 6:21am

say you wanna copy all files with the pattern *blah* to *halb*? for example file_blah.txt would get copied to file_halb.txt can you modify the snippet for that? thanks

Snippets Manager replied on Wed, 2009/02/25 - 12:43pm

Probably better to put a -type f in the find string too... like: find . -name '*.txt' -type f -exec perl -pi -e 's/find/replace/g' {} \; to make sure you're working on a normal file.

Snippets Manager replied on Wed, 2009/02/25 - 12:43pm

instead of using xargs, you can use: find . -name '*.txt' -exec perl -pi -e 's/find/replace/g' {} \; Then it doesn't matter what the filename has in it :-)

Snippets Manager replied on Mon, 2012/03/05 - 3:46am

say you wanna copy all files with the pattern *blah* to *halb*? for example file_blah.txt would get copied to file_halb.txt can you modify the snippet for that? thanksprofessional resume writing services

Snippets Manager replied on Wed, 2007/10/03 - 9:25am

That didn't work when the file names contained white space. This seems to work even with them (with GNU find and xargs): find . -name '*.txt' -print0 |xargs -0 perl -pi -e 's/find/replace/g'