sed命令只替换匹配的括号内的内容

时间:2016-04-05 19:22:41

标签: regex bash sed regex-greedy

我有一些看起来像OldUtility.getList(obj)的旧代码已被重构为obj.getList()。我正在尝试编写一个sed命令,它将正确地重构我的代码。到目前为止,我所拥有的是:

sed -i '' 's/\(OldUtility.getList(\)\(.*\))/\2.getList()/g'

这个问题是它贪婪地抓住了线上的最后一个右括号。这意味着以下情况不起作用:
OldUtility.getList(obj).size()

someFunc(OldUtility.getList(obj), otherObj.otherFunc())

但我不希望它不贪婪,因为它还需要处理如下情况: OldUtility.getList(otherObj.toObj()) - > otherObj.toObj().getList()

所以问题是如何让\2成为OldUtility.getList(...)括号内的所有内容?

3 个答案:

答案 0 :(得分:2)

如果您不想捕捉右括号,则应使用[^)]*代替.*

经过测试:

echo "OldUtility.getList(otherObj.toObj()) OldUtility.getList(obj).size() someFunc(OldUtility.getList(obj), otherObj.otherFunc())" | sed -E 's/OldUtility.getList.([^)]*)\)([\)]*)/\1\2.getList()/g'

命令为sed -E 's/OldUtility.getList.([^)]*)\)([\)]*)/\1\2.getList()/g'

答案 1 :(得分:1)

你让它变得比需要的更复杂。

$ echo "OldUtility.getList(obj)" | sed -r 's/(OldUtility.getList\()[^)]*\)/\1)/'

OldUtility.getList()

我想我误读了参数提取的问题

$ echo "OldUtility.getList(obj)" | sed -r 's/OldUtility(.getList\()([^)]*)\)/\2\1)/'

obj.getList()

最好从搜索模式中捕获字符串值,以消除拼写错误并在一个地方包含值。

看起来我又错过了一次。 这样可以处理另一个级别,但是sed无需前瞻即可处理。

$ echo "OldUtility.getList(otherObj.toObj())" | 
  sed -r 's/OldUtility(.getList\()([^)]+(\(\))?)/\2\1/'

otherObj.toObj().getList()

答案 2 :(得分:1)

由于getList(...)可能会多次包含任何级别的嵌套括号,因此您无法使用sed解决此问题(无法知道哪个右括号是好的)。这是一个可以与Perl一起使用的模式(具有匹配嵌套括号的功能):

OldUtility\.getList\(([^()]*+(?:\((?1)\)[^()]*)*+)\)

详细说明:

OldUtility\.getList\( # Note that the literal dot and parenthesis must be escaped
(            # open capture group 1
    [^()]*+  # all that is not a parenthesis (zero or more)
    (?:           # open a non capturing group
        \((?1)\)  # recursion with the capture group 1 subpattern
        [^()]*
    )*+           # repeat the non-capturing group (zero or more times)
)
\)

示例:

echo 'OldUtility.getList(otherObj.toObj().toString())' | perl -pe 's/OldUtility\.getList\(([^()]*+(?:\((?1)\)[^()]*)*+)\)/$1.getList()/g'
相关问题