bash sed 加号不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22099623/
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
sed plus sign doesn't work
提问by J33nn
I'm trying to replace /./
or /././
or /./././
to /
only in bash script. I've managed to create regex for sed but it doesn't work.
我试图取代/./
或/././
或/./././
以/
仅在bash脚本。我已经设法为 sed 创建正则表达式,但它不起作用。
variable="something/./././"
variable=$(echo $variable | sed "s/\/(\.\/)+/\//g")
echo $variable # this should output "something/"
When I tried to replace only /./
substring it worked with regex in sed \/\.\/
. Does sed regex requires more flags to use multiplication of substring with +
or *
?
当我尝试仅替换/./
子字符串时,它与 sed 中的正则表达式一起使用\/\.\/
。sed regex 是否需要更多标志才能使用子字符串与+
或 的乘法*
?
回答by falsetru
Use -r
option to make sed
to use extended regular expression:
使用-r
选项使sed
使用扩展正则表达式:
$ variable="something/./././"
$ echo $variable | sed -r "s/\/(\.\/)+/\//g"
something/
回答by Scrutinizer
Any sed:
任何 sed:
sed 's|/\(\./\)\{1,\}|/|g'
But a +
or \{1,\}
would not even be required in this case, a *
would do nicely, so
但是在这种情况下甚至不需要a +
or \{1,\}
, a*
会很好,所以
sed 's|/\(\./\)*|/|g'
should suffice
应该足够了
回答by jaypal singh
Two things to make it simple:
两件事使它变得简单:
$ variable="something/./././"
$ sed -r 's#(\./){1,}##' <<< "$variable"
something/
- Use
{1,}
to indicate one or more patterns. You won't needg
with this. - Use different delimiterers
#
in above case to make it readable +
is ERE so you need to enable-E
or-r
option to use it
- 使用
{1,}
以表示一个或多个模式。你不需要g
这个。 #
在上述情况下使用不同的分隔符使其可读+
是 ERE 所以你需要启用-E
或-r
选择使用它
回答by Mark Setchell
You can also do this with bash's built-in parameter substitution. This doesn't require sed
, which doesn't accept -r
on a Mac under OS X:
您也可以使用 bash 的内置参数替换来做到这一点。这不需要sed
,它-r
在 OS X 下的 Mac上不接受:
variable="something/./././"
a=${variable/\/*/}/ # Remove slash and everything after it, then re-apply slash afterwards
echo $a
something/
See herefor explanation and other examples.
有关说明和其他示例,请参见此处。