Issue
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?
Solution
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:
fileLength=$(wc -l file.json | cut -d' ' -f1);
is used to determine the length of the file here5
.$((fileLength-1))s/$/,/;
will add the comma at the end of the 4th line.${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.
Answered By - Allan Answer Checked By - Marie Seifert (WPSolving Admin)