Find and replace text with slash characters

房东的猫 提交于 2019-12-02 03:03:00

问题


So I looked around on Stackoverflow and I understand finding and replacing text works something like this:

perl -pi -w -e 's/www.example.com/www.pressbin.com/g;' *.html

However, what if the text I want to find and replace is a filepath that has slashes? How do I do it then?

perl -pi -w -e 's/path/to/file/new/path/to/file/g;' *.html

回答1:


With perl regexes, you can use any character except spaces as regex delimiter, although

  • Characters in \w (so s xfooxbarx is the same as s/foo/bar/) and
  • Question marks ? (implicitly activates match-only-once behaviour, deprecated) and
  • single quotes '...' (turns of variable interpolation)

should be avoided. I prefer curly braces:

perl -pi -w -e 's{path/to/file}{new/path/to/file}g;' *.html

The delimiting character may not occur inside the respective strings, except when they are balanced braces or properly escaped. So you could also say

perl -pi -w -e 's/path\/to\/file/new\/path\/to\/file/g;' *.html

but that is dowrnright ugly.

When using braces/parens etc there can be whitespace between the regex and the replacement, allowing for beatiful code like

$string =~ s {foo}
             {bar}g;

Another interesting regex option in this context is the quotemeta function. If your search expression contains many characters that would usually be interpreted with a special meaning, we can enclose that string inside \Q...\E. So

m{\Qx*+\E}

matches the exact string x*+, even if characters like *, '+' or | etc. are included.




回答2:


You can use other characters than '/' to specify patterns. For example:

perl -pi -w -e 's,path/to/file,new/path/to/file,g;' *.html



回答3:


perl -pi -w -e 's/path\/to\/file/new\/path\/to\/file/g;' *.html



来源:https://stackoverflow.com/questions/12238384/find-and-replace-text-with-slash-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!