Reputation: 2866
I have a bash script that output json, but apparently, I can't have a comma at the end of the list items as seen below. How do I get the last item in the list to not have a comma on the end, while keeping it on all the rest of the items?
Ideally, I'd like to do this in the loop, but I'm okay with stripping it off after creation.
Here is a portion of the script.
#Print out a list of hosts in groups
for group in $grouplist; do
printf '\t"%s": {\n' $group
echo -ne '\t\t"hosts": ['
for host in `grep $group $results|awk '{print $1}'`; do
printf '"%s", ' "$host"
done
echo ']'
echo -e '\t},'
done
It outputs a json list ending like this.
},
}
I have this in a function so I have messed around with a variety of sed stuff to clean it up, but haven't managed to pull it off.
function | sed "s/something/another/"
Upvotes: 0
Views: 357
Reputation: 2356
Maybe you can get the len of $grouplist
and keep track of the loop count, then echo with and if;then; else, something like this:
len=$(wc -w <<< $grouplist)
i=0
for group in $grouplist; do
let i++
printf '\t"%s": {\n' $group
echo -ne '\t\t"hosts": ['
for host in `grep $group $results|awk '{print $1}'`; do
printf '"%s", ' "$host"
done
echo ']'
if (( $i < $len )); then
echo -e '\t},'
else
echo -e '\t}'
fi
done
Upvotes: 2