Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix find and replace recursively?

Tags:

find

replace

unix

Hopefully, this will be a quick one for someone here... I need to find and replace a string recursively in unix.

Normally, I use:

perl -e "s/term/differenterm/g;" -pi $(find path/to/DIRECTORY -type f)

But, the string I need to replace contains slashes, and I'm not sure how to escape them?

So, I need to do:

perl -e "s/FIND/REPLACE/g;" -pi $(find path/to/DIRECTORY -type f)

where FIND = '/string/path/term' and REPLACE = '/string/path/newterm'

like image 998
user1154488 Avatar asked Dec 17 '22 01:12

user1154488


2 Answers

You could use other characters besides /. For example:

perl -e "s|FIND|REPLACE|g;" -pi $(find path/to/DIRECTORY -type f)

More info in http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators

like image 166
luis.parravicini Avatar answered Jan 10 '23 23:01

luis.parravicini


In unix it goes something like this:

find "$path" -type f -print0|xargs -0 \
    perl -p -i -e "s/term/differenterm/g;"

This makes use of find and xargs to find all files in a subtree and pass them to perl for processing.

Note, if you want to use /'s in your regex, you can either escape them with a \:

    perl -p -i -e "s/\/source\/path/\/dest\/path/g;"

or use a different delimiter than / for the regex itself:

    perl -p -i -e "s|/source/path|/dest/path|g;"

Note also, there are other ways of running a program on a subtree recursively, but they do not all properly handle filenames with spaces or other special charaters.

like image 45
Michael Slade Avatar answered Jan 10 '23 22:01

Michael Slade