muzafarow muzafarow - 5 months ago 9x
Bash Question

How delete last comma in json file using Bash?

I wrote some script that takes all user data of aws ec2 instance, and echo to local.json. All this happens when I install my node.js modules.
I don't know how to delete last comma in the json file. Here is the bash script:

export DATA_DIR=/data
export PATH=$PATH:/usr/local/bin

#install package from git repository
sudo -- sh -c "export PATH=$PATH:/usr/local/bin; export DATA_DIR=/data; npm install git+$1.git#$2"

#update config files from instance user-data
InstanceConfig=`cat /instance-config`
echo '{' >> node_modules/$1/config/local.json
while read line
if [ ! -z "$line" -a "$line" != " " ]; then
Key=`echo $line | cut -f1 -d=`
Value=`echo $line | cut -f2 -d=`
if [ "$Key" = "Env" ]; then
printf '"%s" : "%s",\n' "$Key" "$Value" >> node_modules/*/config/local.json
done <<< "$InstanceConfig"
sed -i '$ s/.$//' node_modules/$1/config/local.json
echo '}' >> node_modules/$1/config/local.json

To run him im doing that way: ./script
I get json(OUTPUT), but with comma in all lines. Here is local.json that I get:

"Env" : "dev",
"EngineUrl" : "",

All I trying to do, is delete in last line of the json file - comma(",").
I try many ways, that I found in internet. I know that it should be after last "fi"(end of the loop). And I know that it should be something like this line:

sed -i "s?${Key} : ${Value},?${Key} : ${Value}?g" node_modules/$1/config/local.json

Or this:

sed '$ s/,$//' node_modules/$1/config/local.json

But they not work for me.
Can someone help me with that? Who knows Bash scripting well?


If you know that it is the last comma that needs to be replaced, a reasonably robust way is to use GNU sed in "slurp" mode like this:

sed -zr 's/,([^,]*$)/\1/' local.json


"Env" : "dev",
"EngineUrl" : ""