我正在使用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
方括号之间的项目?
答案 0 :(得分:5)
你可以试试这个,
sed -i.bak -r "s#(\[[^]]*)$a( [^[]*\])#\1$b\2#g" ./file.txt