Vivek Puri
Vivek Puri

Reputation: 171

Insert after a string in a file using sed

I want to add some content to the file "file.txt" which is having text

"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

I want to add text after "body":" in the file. I was trying

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

but nothing happens. Am i wrong somewhere? I am not able to find the solution to this problem. I searched alot on google.

Upvotes: 0

Views: 62

Answers (2)

Ports
Ports

Reputation: 429

... or even shorter (use the appropriate flag, eg: -i or --in-place):

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

If you want to substitute $var1 and $var2 with their respective values, you could try the following:

$ 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

Upvotes: 1

Mehdi Yedes
Mehdi Yedes

Reputation: 2375

Try this variant:

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

This is the the content of file.txt after running the sed command:

"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"}]

Upvotes: 1

Related Questions