搜索字符串并在行末添加字符串但在引号之前使用sed

时间:2017-10-13 09:07:43

标签: linux bash shell sed

我正在寻求帮助以找到字符串并在行末添加字符串但在引号

之前

文件输出:

 I have a file
 search_string="It has some text"
 some other text

我试过以下方法:

 sed -i '/^search_string=/ s/$/ add_string one add_string two/' file

我的输出低于输出:

 I have a file
 search_string="It has some text" add_string one add_string two
 some other text

预期产出:

 I have a file
 search_string="It has some text add_string one add_string two"
 some other text

3 个答案:

答案 0 :(得分:4)

$ sed 's/search_string="[^"]*/& add_string_one add string two/' file

您可以使用-i

就地执行此操作
$ sed -i.bak 's/search_string="[^"]*/& add_string_one add string two/' file

$ diff file.bak file
2c2
< search_string="It has some text"
---
> search_string="It has some text add_string_one add string two"

答案 1 :(得分:0)

sed '/^.*search_string=/ s/\(.*\)"/\1 add_string one add_string two"/' file

答案 2 :(得分:0)

对OP代码的简单修改

textarea
  • $ sed '/^search_string=/ s/"$/ add_string one add_string two"/' file I have a file search_string="It has some text add_string one add_string two" some other text 匹配行尾的双引号
  • 在替换部分,也添加引用

或者为避免重复较长文字的文字,请使用"$。例如:

&