Forked from rbhushan90/MySQL dump into CSV text files with column names at the top?
Created
February 10, 2020 15:59
-
-
Save AdnaneX/edb4b277204fb701de38e58e77f99856 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DBNAME=<database_name> | |
TABLE=<table_name> | |
FNAME=/path/to/output/dir/$(date +%Y.%m.%d)-$DBNAME.csv | |
#(1)creates empty file and sets up column names using the information_schema | |
mysql -u <username> -p<password> $DBNAME -B -e "SELECT COLUMN_NAME FROM information_schema.COLUMNS C WHERE table_name = '$TABLE';" | awk '{print $1}' | grep -iv ^COLUMN_NAME$ | sed 's/^/"/g;s/$/"/g' | tr '\n' ',' > $FNAME | |
#(2)appends newline to mark beginning of data vs. column titles | |
echo "" >> $FNAME | |
#(3)dumps data from DB into /var/mysql/tempfile.csv | |
mysql -u <username> -p<password> $DBNAME -B -e "SELECT * INTO OUTFILE '/var/mysql/tempfile.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' FROM $TABLE;" | |
#(4)merges data file and file w/ column names | |
cat /var/mysql/tempfile.csv >> $FNAME | |
#(5)deletes tempfile | |
rm -rf /var/mysql/tempfile.csv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How about