Gossamer Forum
Home : General : Internet Technologies :

How to search and replace with grep?

Quote Reply
How to search and replace with grep?
hi,

can anyone tell me how to search and replace a path in text files using grep?

I want to change a file path in settings files... eg...

from this "/this/is/my/path/" to this "/this/is/my/path2/"

regan.
Quote Reply
Re: [ryel01] How to search and replace with grep? In reply to
You'll probably want to use perl for that. As usual there's a ton of approaches to this. One way is to use grep to find files which you want to perform the replacement on and then pass the file list to perl to replace:
Code:
grep -rl 'some posix regex here' * | xargs perl -p -i -e 's/replacethis/withthis/'
and then if you want, you can use find to get a filelisting and pass them all through perl:
Code:
find . -type f -iname '*.pm' | xargs perl -p -i.bak -e 's/replacethis/withthis/'
Where 'find' will recursively list all .pm files in the current directory, and perl will perform the regex, making a backup (to filename.pm.bak) of all replaced files. Of course the "-iname '*.pm'" part is optional, just leave it out to do the replacement on all files. The .bak part of the -i in the perl arguments is also optional. Leave it out to not make any backups - just make sure your regex works Wink

oops, fixed.

Adrian

Last edited by:

brewt: Sep 18, 2003, 12:08 PM
Quote Reply
Re: [brewt] How to search and replace with grep? In reply to
I think you need a -l in your grep there, and a -e in your second perl. =)

Cheers,

Alex
--
Gossamer Threads Inc.
Quote Reply
Re: [brewt] How to search and replace with grep? In reply to
in case anyones interested this is what i ended up using....

starting in a directory, run the following code (with your own paths etc) and it will go through all the files and folders recursively below that point replacing all the found instances with your new path.

Code:
find . -exec grep -l "/path/you/want/to/find" {} \; | xargs perl -p -i -e 's/\/path\/you\/want\/to\/find/\/path\/to\/replace\/it\/with/';

Unfortunately it will spit a list of the folders it finds back at you - if anyone knows how to stop that please let me know! :)

cheers!

r

Last edited by:

ryel01: Mar 13, 2004, 7:04 PM
Quote Reply
Re: [ryel01] How to search and replace with grep? In reply to
This is a grep command Alex gave to me;

Code:
cd /path/to/admin
perl -p -i -e 's|\Q/old/path|/new/path|g' `grep -r -l '/path/to/change' .`

... as Alex said to me, you need to be careful which files you are editing. To see a list of these files, type;

Code:
grep -r -l '/path/to/change' .

.. and this will bring up a list of files that will be edited.

Cheers

Andy (mod)
andy@ultranerds.co.uk
Want to give me something back for my help? Please see my Amazon Wish List
GLinks ULTRA Package | GLinks ULTRA Package PRO
Links SQL Plugins | Website Design and SEO | UltraNerds | ULTRAGLobals Plugin | Pre-Made Template Sets | FREE GLinks Plugins!