我知道bash的各种string操作function。
此外,我知道我可以逃避特殊模式字符与反斜杠\
。
例如:
# x is a literal string 'foo*bar' x="foo*bar" # prints "*bar". echo "${x##foo}" # prints nothing, since the '*' is interpreted as a glob. echo "${x##foo*}" # prints "bar", since I escaped the '*'. echo "${x##foo\*}"
以上都很好,很好。 问题是当模式从其他地方进入时,它可能没有*
和其他特殊符号字符转义。
例如:
prefix="foo*" ... later, in some faraway code ... x="foo*bar" # I want this to print 'bar'. So I want the '*' to be escaped. But how? echo "${x##$prefix}"
基本上,我正在寻找类似于Perl的quotemeta函数的东西。
在bash中是否有这样的东西?
啊,我在发布之后就明白了这一点。
答案(一如既往)是:添加更多的引号(:
对于我的例子:
prefix="foo*" ... later, in some faraway code ... x="foo*bar" # Prints 'bar' since the pattern has double-quotes surrounding it. echo "${x##"$prefix"}"