bash 如何使用 SED 查找和替换目标字符串中带有“/”字符的 URL 字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16778667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:46:29  来源:igfitidea点击:

How to use SED to find and replace URL strings with the "/" character in the targeted strings?

bashsedescaping

提问by LearnWebCode

I'm attempting to use SED through OS X Terminal to perform a find and replace.

我正在尝试通过 OS X 终端使用 SED 来执行查找和替换。

Imagine I have this string littered throughout the text file: http://www.find.com/page

想象一下,这个字符串散落在整个文本文件中:http: //www.find.com/page

And I want to replace it with this string: http://www.replace.com/page

我想用这个字符串替换它:http: //www.replace.com/page

I'm having trouble because I'm not sure how to properly escape or use the "/" character in my strings. For example if I simply wanted to find "cat" and replace with "dog" I've found the following command that works perfectly:

我遇到了麻烦,因为我不确定如何正确转义或在我的字符串中使用“/”字符。例如,如果我只是想找到“cat”并替换为“dog”,我发现以下命令非常有效:

sed -i '' 's/cat/dog/g' file.txt

Does anyone have any ideas on how to achieve the same functionality only instead of cat and dog have strings or URLs that container the "/" character? I tried many different ways of escaping the "/" characters but then it seems as if SED can no longer "find" the string and it doesn't perform any find & replace actions.

有没有人对如何实现相同的功能有任何想法,而不是 cat 和 dog 具有包含“/”字符的字符串或 URL?我尝试了许多不同的转义“/”字符的方法,但似乎 SED 无法再“找到”字符串并且它不执行任何查找和替换操作。

Any help or tips are greatly appreciated.

非常感谢任何帮助或提示。

Thanks!

谢谢!

回答by Joachim Isaksson

/is not thedelimiter in sedcommands, it's just one of the possible ones. For this example, you can for example use ,instead since it does not conflict with your strings;

/不是命令中分隔符sed,它只是可能的分隔符之一。对于此示例,您可以例如使用,,因为它不会与您的字符串冲突;

echo 'I think http://www.find.com/page is my favorite' | 
    sed 's,http://www.find.com/page,http://www.replace.com/page,g'

回答by jaypal singh

sedcan take whatever follows the "s" as the separator. Since you are working with URLit is a good practice to use a different delimiter other than /to not confuse sedwhen your substitution ends and replacement begins.

sed可以将“s”后面的任何内容作为分隔符。由于您正在使用URL它,因此最好使用不同的分隔符,/而不是sed在替换结束和替换开始时混淆。

However, having said that you can definitely use /if you wish too. You just need to escape the literal /.

但是,话虽如此,/如果您愿意,您绝对可以使用。您只需要转义文字/.

So, you can either do:

所以,你可以这样做:

sed 's/http:\/\/www.find.com\/page/http:\/\/www.replace.com\/page/g' input_file

or use a different delimiter to avoid making your cryptic sed more cryptic.

或使用不同的分隔符以避免使您的神秘 sed 更加神秘。

sed 's#http://www.find.com/page#http://www.replace.com/page#g' input_file