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

Vil*_*age -2 replace sed

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

    sed -i "s/$a/$b/g" ./file.txt
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

假设$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.
Run Code Online (Sandbox Code Playgroud)
  • 打开和关闭方括号始终显示在同一行上.

我怎样才能找到并替换那些出现在方括号之间的项目sed?

sat*_*sat 5

你可以试试这个,

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