4

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'

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

@user1154488 says term and differentterm contains slashes so your solution doesn't solve his problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.