bash 如何使用sed从bash中的字符串中删除转义字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15244801/
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
How to remove escape char from string in bash using sed?
提问by user1581900
I need to remove escape character from the string in bash. I get a data structure, which contains url paths with / escaped so I receive the regular link:
我需要从 bash 的字符串中删除转义字符。我得到一个数据结构,其中包含带有 / 转义的 url 路径,因此我收到了常规链接:
http://stackoverflow.com/questions/ask
as one with escaped /:
作为转义 / 之一:
http:\/\/stackoverflow.com\/questions\/ask
Now I need to remove \ from the second link. For this purpose I tried using sed
现在我需要从第二个链接中删除 \。为此,我尝试使用 sed
`echo '"'${paths[$index]}'"' | sed "s@\@@g"`
But I get an error:
但我收到一个错误:
sed: -e expression #1, char 6: unterminated `s' command
If I replace \\ with ie. _ it works like a charm and removes all occurrences of _ in a string. How do I get rid of escape characters in a string using sed?
如果我用 ie 替换 \\ 。_ 它就像一个魅力,并删除字符串中所有出现的 _。如何使用 sed 去除字符串中的转义字符?
回答by Kent
try this:
尝试这个:
.......|sed 's@\@@g'
or:
或者:
.......|sed "s@\\@@g"
EDITadd a test output:
编辑添加一个测试输出:
kent$ echo "http:\/\/stackoverflow.com\/questions\/ask"|sed "s@\\@@g"
http://stackoverflow.com/questions/ask
kent$ echo "http:\/\/stackoverflow.com\/questions\/ask"|sed 's@\@@g'
http://stackoverflow.com/questions/ask
回答by Chris Seymour
Your question isn't clear about which way round you want so here is both ways:
您的问题不清楚您想要哪种方式,所以这里有两种方式:
$ sed 's@/@\/@g' <<< "http://stackoverflow.com/questions/ask"
http:\/\/stackoverflow.com\/questions\/ask
$ sed 's@\/@/@g' <<< "http:\/\/stackoverflow.com\/questions\/ask"
http://stackoverflow.com/questions/ask
回答by chepner
You don't need to use sed.
您不需要使用sed.
paths[index]=${paths[index]//\/}
or simply
或者干脆
echo ${paths[index]//\/}
to see the result without modifying the value in-place.
在不修改值的情况下查看结果。
回答by Arjun Bhandage
You can use this :
你可以使用这个:
sed 's@\@@g'
But the problem is when you encounter a backslash that you actually want in the string, but is escaped. In that case :
但问题是当您在字符串中遇到您实际想要的反斜杠但被转义时。在这种情况下 :
sed 's/\\/\x1/' |sed 's/[\]//g' | sed 's/\x1/\/g'
Replaces the double backslash with with a temp character[SOH], replaces all other backslashes and then restores the backslash that is needed.
用临时字符 [SOH] 替换双反斜杠,替换所有其他反斜杠,然后恢复所需的反斜杠。

