Skip to content

Instantly share code, notes, and snippets.

@ldotlopez
Created September 12, 2023 08:23
Show Gist options
  • Save ldotlopez/0eb44e5d8aaf0bf18ca40633dea6abfb to your computer and use it in GitHub Desktop.
Save ldotlopez/0eb44e5d8aaf0bf18ca40633dea6abfb to your computer and use it in GitHub Desktop.
sqlite3-csv
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
# shellcheck disable=SC2034
__FILE__="$(realpath -- "${BASH_SOURCE[0]}")"
__DIR__="$(dirname -- "$__FILE__")"
__NAME__="$(basename -- "$__FILE__")"
function log() {
local -a OPTS=("-t" "$__NAME__")
logger "${OPTS[@]}" "$@"
}
function is_main() {
[[ -z "$BASH_VERSION" ]] && {
echo "This script must be run under bash" >&2
exit 255
}
[[ "${BASH_SOURCE[0]}" = "${0}" ]] || return 1
return 0
}
function main() {
CSVFILE="$1"
# NAME="$(basename -- "$(realpath -- "$CSVFILE")")"
# NAME="${NAME%.csv}"
echo "[*] CSV data available in the 'csv' table"
sqlite3 :memory: \
-cmd '.mode csv' \
-cmd ".import '$CSVFILE' csv" \
-cmd '.headers on' \
-cmd '.mode table'
}
function usage() {
echo "Usage: $__NAME__ file.csv" >&2
exit 1
}
if is_main; then
if [[ $# -ne 1 ]]; then
usage
fi
CSVFILE="$1"
if [[ ! -e "$CSVFILE" ]] || [[ ! -r "$CSVFILE" ]]; then
echo "${__NAME__}: File not found or not readable: $CSVFILE"
exit 2
fi
main "$CSVFILE"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment