CSV to SQLite Database
- Details
- Category: linux
- Published on Saturday, 28 April 2012 01:05
- Written by Reuben
- Hits: 157
Just wrote a bash script to import a CSV file with headers (and without double quotes) into an sqlite database:
#!/bin/bash if [ "$3" = "" ]; then echo "Enter \"csv2sql filename tablename dbname\""; else filename=$1 tablename=$2 dbname=$3 list=$(cat $filename | sed -n '1p' | sed 's/,/ VARCHAR,/g') cat $filename | sed '1d' | sed 's/,/|/g' > temp echo "create table $tablename($list VARCHAR);" | sqlite3 $dbname echo ".import temp $tablename" | sqlite3 $dbname rm temp fi
Oh and this allows you to create a new db and table as well. If your CSV file comes with double quotes for strings, you may wanna add the following line at the start:
sed 's/"//g' $filename > temp; mv $filename $filename".bak"; mv temp $filename



