Skip to content

Instantly share code, notes, and snippets.

@trastle
Last active December 16, 2015 01:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trastle/5353664 to your computer and use it in GitHub Desktop.
Save trastle/5353664 to your computer and use it in GitHub Desktop.
Converts an input file into a JSON array. Each line of the file will become an element in the array.
#!/bin/bash
DATA_FILE="$1"
OUT_FILE="$DATA_FILE.json"
if [ ! -f "$DATA_FILE" ]; then
echo "Data file is missing please specify a data file on the command line."
exit 1
fi
if [ -f "$OUT_FILE" ]; then
echo "Output file exists at $OUT_FILE remove it and try again."
exit 1
fi
# Start the array.
touch "$OUT_FILE"
echo "[" >> "$OUT_FILE"
# Add all the data
cat "$DATA_FILE" | sed 's/.*$/&,/' >> "$OUT_FILE"
# Remove the final comma
mv "$OUT_FILE" "$OUT_FILE.temp"
sed '$ s/,$//' "$OUT_FILE.temp" > "$OUT_FILE"
rm "$OUT_FILE.temp"
# Finish the array
echo "]" >> "$OUT_FILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment