Skip to content

Instantly share code, notes, and snippets.

@Vesihiisi
Last active March 16, 2016 10:41
Show Gist options
  • Save Vesihiisi/ee14c90210c971827784 to your computer and use it in GitHub Desktop.
Save Vesihiisi/ee14c90210c971827784 to your computer and use it in GitHub Desktop.
#!/bin/bash
IFS=","
output_file="salar.json"
rm -f "$output_file"
awk 'NR>1' salar.csv > salar_clean.csv
read first < salar_clean.csv
Headers=($first)
awk 'NR>1' salar_clean.csv > salar_cleaner.csv
total_lines=$(wc -l < "salar_cleaner.csv")
{
echo "{"
echo -n "\"salar\""
echo ":"
echo "["
} >> "$output_file"
line_counter=0
while read f1 f2 f3 f4 f5 f6 f7 f8 f9
do
(( line_counter ++ ))
echo "{" >> "$output_file"
declare -a fields_in_line
fields_in_line=("$f1" "$f2" "$f3" "$f4" "$f5" "$f6" "$f7" "$f8" "$f9")
iteration=0
for i in "${fields_in_line[@]}"
do
(( iteration ++ ))
let "index_to_access=iteration-1"
header="${Headers[$index_to_access]}"
echo -n "\"$header\" : " >> "$output_file"
if [ ${#i} -eq 0 ]; then
echo -n "null" >> "$output_file"
else
echo -n "\"$i\"" >> "$output_file"
fi
if [ "$iteration" -ne "${#fields_in_line[@]}" ]; then
echo "," >> "$output_file"
else
echo "" >> "$output_file"
fi
done
echo -n "}" >> "$output_file"
if [ "$line_counter" -ne "$total_lines" ]; then
echo "," >> "$output_file"
else
echo "" >> "$output_file"
fi
done < salar_cleaner.csv
echo "]" >> "$output_file"
echo "}" >> "$output_file"
rm -f "salar_cleaner.csv"
rm -f "salar_clean.csv"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment