replace URL using shell script

2019-02-16 03:30发布

问题:

I am getting below error while I try to replace one url? What is the efficient way to replace URL in all files in a give directory.

sed: -e expression #1, char 62: unknown option to `s'

find . -name '*' | xargs sed -i 's/old_url/new_url/g' did not work

回答1:

Here's a way to do it in perl.

cd directory
perl -pi -e 's!old_url!new_url!g;' *


回答2:

The fundamental problem is probably that you are specifying something like

s/http://example.com/ick/poo/http://example.net/also/not/

which is not a valid sed or perl script, and obviously quite ambiguous. Use an alternate separator which is not anywhere in either the regular expression or in the replacement; a popular choice is !

s!http://example.com/ick/poo!http://example.net/also/not!

which is valid in both sed and perl.

Edit Kudos to @TLP for also diagnosing this in a comment. I'll remove this answer if you post a similar one.



回答3:

Or using find as in your original question:

find . -type f -exec perl -pi -e 's{old_url}{new_url}g' {} +

And if Perl is telling you "no such file or directory," it's probably because you accidentally omitted the -e

EDIT: changed s///gs to s{}{}g since, as TLP pointed out, you're working with URLs.

EDIT: changed \; to + per ikegami's suggestion.



标签: perl replace sed