如何查找和替换方括号之间出现的项目与sed?

时间:2013-07-16 06:20:53

标签: replace sed

我正在使用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方括号之间的项目?

1 个答案:

答案 0 :(得分:5)

你可以试试这个,

sed -i.bak -r "s#(\[[^]]*)$a( [^[]*\])#\1$b\2#g" ./file.txt