Skip to content

Instantly share code, notes, and snippets.

@ryantuck
Created August 19, 2016 23:51
Show Gist options
  • Save ryantuck/d4bb8cfeb5a82e1021c8911b692ba588 to your computer and use it in GitHub Desktop.
Save ryantuck/d4bb8cfeb5a82e1021c8911b692ba588 to your computer and use it in GitHub Desktop.
generate a .csv from a .sql file query
#!/bin/bash
# executes a .sql file and outputs results to a .csv
# ./sql_to_csv.sh my_query.sql output.csv
CONN="psql -U my_user -d my_db"
# remove all semicolons and comments
# replace newlines with spaces
QUERY="$(sed 's/;//g;/^--/ d;s/--.*//g;' $1 | tr '\n' ' ')"
echo "$QUERY"
echo "\\copy ($QUERY) to '$2' with csv header" | $CONN > /dev/null
@Cbeck527
Copy link

💯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment