使用sed在文件中的字符串后面插入

时间:2016-02-01 15:04:39

标签: string bash sed

我想在文件“file.txt”中添加一些内容

"textcolor": [0.9333333333333333, 0.9333333333333333,
0.9254901960784314]}}, "notes": [{"last_modified": "2016-02-
01T16:00:42", "uuid": "2a6063b8-accd-458a-a5ca-18c8c86a6767", 
"body":"\n1. Braggadocio : 1. empty or pretentious boasting. 2. a 
braggart.\n2. Ichor : 1. the rarefied fluid running in the veins of 
gods. 2. a watery acrid discharge from a wound or ulcer.\n

我想在“body”之后添加文字:“在文件中。我正在尝试

sed -i  '/"body":"/a $i. "$var1 $var2\n"' file.txt 

但没有任何反应。我错了吗?我无法找到解决此问题的方法。我在谷歌搜索了很多。

2 个答案:

答案 0 :(得分:1)

尝试此变体:

sed --in-place 's/"body":"/"body":"a $i. "$var1 $var2\\n"/g' file.txt

这是运行file.txt命令后sed的内容:

"textcolor": [0.9333333333333333, 0.9333333333333333,
0.9254901960784314]}}, "notes": [{"last_modified": "2016-02-
01T16:00:42", "uuid": "2a6063b8-accd-458a-a5ca-18c8c86a6767", 
"body":"a $i. "$var1 $var2\n"\n1. Braggadocio : 1. empty or pretentious     boasting. 2. a 
braggart.\n2. Ichor : 1. the rarefied fluid running in the veins of 
gods. 2. a watery acrid discharge from a wound or ulcer.\n"}]

答案 1 :(得分:1)

......甚至更短(使用适当的标志,例如:-i或--i​​n-place):

sed 's/"body":"/&a $i. "$var1 $var2\\n"/g' text.txt 

如果您想将$ var1和$ var2替换为各自的值,可以尝试以下方法:

$ var1="AAA"
$ var2="BBB"
$ sed "s/\"body\":\"/&a \$i. $var1 $var2\\n/g" text.txt
"textcolor": [0.9333333333333333, 0.9333333333333333,
0.9254901960784314]}}, "notes": [{"last_modified": "2016-02-
01T16:00:42", "uuid": "2a6063b8-accd-458a-a5ca-18c8c86a6767", 
"body":"a $i. AAA BBB
\n1. Braggadocio : 1. empty or pretentious boasting. 2. a 
braggart.\n2. Ichor : 1. the rarefied fluid running in the veins of 
gods. 2. a watery acrid discharge from a wound or ulcer.\n