Skip to content

Instantly share code, notes, and snippets.

@anhqle
Created July 16, 2014 15:06
Show Gist options
  • Save anhqle/ee3b2088b442093602b0 to your computer and use it in GitHub Desktop.
Save anhqle/ee3b2088b442093602b0 to your computer and use it in GitHub Desktop.
A Shell script that import CSV into MySQL by automatically creating the table structure. This is more convenient than the `LOAD DATA INFILE` command, which requires us to manually create the MySQL database first
#!/bin/sh
MYSQL_ARGS="--defaults-file=/etc/mysql/debian.cnf"
DB="mbctest"
DELIM=";"
CSV="$1"
TABLE="$2"
[ "$CSV" = "" -o "$TABLE" = "" ] && echo "Syntax: $0 csvfile tablename" && exit 1
FIELDS=$(head -1 "$CSV" | sed -e 's/'$DELIM'/` varchar(255),\n`/g' -e 's/\r//g')
FIELDS='`'"$FIELDS"'` varchar(255)'
#echo "$FIELDS" && exit
mysql $MYSQL_ARGS $DB -e "
DROP TABLE IF EXISTS $TABLE;
CREATE TABLE $TABLE ($FIELDS);
LOAD DATA INFILE '$(pwd)/$CSV' INTO TABLE $TABLE
FIELDS TERMINATED BY '$DELIM'
IGNORE 1 LINES
;
"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment