djl
djl

Reputation: 277

Using sed to add line to end of .JSON file

I have a .json file that looks something like this:

{
    "Direction": "down",
    "Conversion": "Complete",
    "Version": "v1.0.20170724"
}

I want to add a line to the end, so I did this:

sed -i '$s/}/,\t"Task":"Yes"}/' data.json

Which changes the file to this:

{
    "Direction": "down",
    "Conversion": "Complete",
    "Version": "v1.0.20170724"
,   "Task":"Yes"
}

Is there a way to have the comma be at the end of second to last line rather than on the last line?

Upvotes: 3

Views: 1662

Answers (3)

hschou
hschou

Reputation: 215

If the JSON file is formatted with indents then search for the one and only } in the end. Then insert a line before that.

sed -i '/^}/i,   "Task":"Yes"' data.json

Eventually run a JSON lint afterwards:

python -mjson.tool data.json

Upvotes: 0

potong
potong

Reputation: 58478

This might work for you (GNU sed):

sed 'N;/\n}/{s//,&/;P;s/".*,/"Task":"Yes"/};P;D' file

Read two lines at a time into the pattern space. If the second line begins with }, insert a , before the newline, print the amended first line, substitute the new values into the first line and repeat.

Upvotes: 1

Allan
Allan

Reputation: 12448

You can use the following sed command for this purpose:

$ cat -vTE file.json 
{$
^I"Direction": "down",$
^I"Conversion": "Complete",$
^I"Version": "v1.0.20170724"$
}$

$ fileLength=$(wc -l file.json | cut -d' ' -f1); sed "$((fileLength-1))s/$/,/; ${fileLength}i  \\\t\"Task\":\"Yes\"" file.json                 
{
        "Direction": "down",
        "Conversion": "Complete",
        "Version": "v1.0.20170724",
        "Task":"Yes"
}

Explanations:

  1. fileLength=$(wc -l file.json | cut -d' ' -f1); is used to determine the length of the file here 5.
  2. $((fileLength-1))s/$/,/; will add the comma at the end of the 4th line.
  3. ${fileLength}i \\\t\"Task\":\"Yes\" is used to insert "Task":"Yes" just before last line!

You can redirect the output of the command to a new file or use sed -i.bak to activate inline mode and make the changes directly in the file.

Upvotes: 1

Related Questions