-2

sed用来查找和替换文件中的某些项目,如下所示:

    sed -i "s/$a/$b/g" ./file.txt

我需要将此查找和替换限制为仅当匹配文本位于方括号之间时,例如:

The sheep lived in the barn.
One day, [the sheep ate some] grass.
The [sheep] found a nice place to sleep under the tree.
Afterwards, [the sheep ate apples under] the tree [near the barn].
The sheep [enjoyed the theme] of the movie.

假设$a设置为“the”并$b设置为“B”,输出将如下所示:

The sheep lived in the barn.
One day, [B sheep ate some] grass.
The [sheep] found a nice place to sleep under the tree.
Afterwards, [B sheep ate apples under] the tree [near B barn].
The sheep [enjoyed B theme] of the movie.
  • 左方括号和右方括号总是出现在同一行。

如何仅查找和替换出现在方括号之间的那些项目sed

4

1 回答 1

5

你可以试试这个

sed -i.bak -r "s#(\[[^]]*)$a( [^[]*\])#\1$b\2#g" ./file.txt
于 2013-07-16T07:01:06.313 回答