joe
joe

Reputation: 21

Combining two files into single file

I have the below script which combines many json files into single one. But the first file is printed twice in final output file even though i have removed the first file from the list.Please advice how to print first file only once. Bash Script is pasted below.

#!/bin/bash
shopt -s nullglob
declare -a jsons
jsons=(o-*.json) 
echo '[' > final.json
if [ ${#jsons[@]} -gt 0 ]; then 
cat "${jsons[0]}" >> final.json 
unset $jsons[0]                    
for f in "${jsons[@]}"; do # iterate over the rest
echo "," >>final.json
cat "$f" >>final.json
done
fi
echo ']' >>final.json         

Upvotes: 0

Views: 56

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95634

You can't use unset ${foo[0]} to remove an item from an array variable in bash.

$ foo=(a b c)
$ echo "${foo[@]}"
a b c
$ unset ${foo[0]}
$ echo "${foo[@]}"
a b c

You'll need to reset the array itself using array slicing.

$ foo=("${foo[@]:1}")
$ echo "${foo[@]}"
b c

See: How can I remove an element from an array completely?

Upvotes: 1

Related Questions