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'
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With