Skip to content

Instantly share code, notes, and snippets.

@mutovkin
Created April 29, 2024 19:35
Show Gist options
  • Save mutovkin/acbb78e143ed587654aa5f5436d427a7 to your computer and use it in GitHub Desktop.
Save mutovkin/acbb78e143ed587654aa5f5436d427a7 to your computer and use it in GitHub Desktop.
Converts CSV file into a table in SQLite Database
#!/usr/bin/env bash
# This script accepts 3 parameters:
# 1. CSV file to import (should have first row as a header and names should not contain dashes, all lower case)
# 2. Database filename where the csv file will be imported (filename should have .db extension)
# 3. Table name where the csv file will be imported (table name should not contain dashes, all lower case)
CSV_FILE=$1
DB_FILE=$2
TABLE_NAME=$3
# Check if the first argument is a csv file
if [ -z ${CSV_FILE} ]; then
echo "Usage: import_csv_to_sqlite.sh <csv_file> <db_file> <table_name>"
exit 1
fi
# check if filename ends with .csv
if [[ ${CSV_FILE} != *.csv ]]; then
echo "Error: ${CSV_FILE} is not a csv file."
exit 1
fi
# Check if the csv file exists
if [ ! -f ${CSV_FILE} ]; then
echo "Error: ${CSV_FILE} does not exist."
exit 1
fi
# Check if the sqlite3 command exists
if ! command -v sqlite3 &> /dev/null; then
echo "Error: sqlite3 command was not found."
exit 1
fi
# Check if the second argument is a db file
if [ -z ${DB_FILE} ]; then
echo "Usage: import_csv_to_sqlite.sh <csv_file> <db_file> <table_name>"
exit 1
fi
# check if filename ends with .db
if [[ ${DB_FILE} != *.db ]]; then
echo "Error: ${DB_FILE} is not a db file."
exit 1
fi
# Check if the third argument is a table name
if [ -z ${TABLE_NAME} ]; then
echo "Usage: import_csv_to_sqlite.sh <csv_file> <db_file> <table_name>"
exit 1
fi
# check if table name contains dashes
if [[ ${TABLE_NAME} == *-* ]]; then
echo "Error: Table name should not contain dashes."
exit 1
fi
# convert table name to lower case
TABLE_NAME=$(echo ${TABLE_NAME} | tr '[:upper:]' '[:lower:]')
# This script will convert a CSV file to a SQLite database.
sqlite3 ${DB_FILE} <<EOS
.mode csv
.import ${CSV_FILE} ${TABLE_NAME}
EOS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment