Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Last active January 14, 2016 11:25
Show Gist options
  • Save coderofsalvation/466d7da29a89980399b4 to your computer and use it in GitHub Desktop.
Save coderofsalvation/466d7da29a89980399b4 to your computer and use it in GitHub Desktop.
quote-safe way to extract field(s) from a csv using awk (bashfunction)
# usage: cat my.csv | csvget 2 (outputs: "foo bar")
# @dependency: gawk
[[ ! -n $SEP ]] && SEP=','
[[ ! -n $SEPOUT ]] && SEPOUT=$SEP
csvget(){
local fields="$*" ; fields="\$${fields// /\"$SEPOUT\"\$}"
cat - | sed 's/""/" "/g' | gawk -vFS='^"|"'$SEP'"|"$|"'$SEP'|'$SEP'"|'$SEP '{ sub(".*" $1 FS,""); print '${fields}' }'
}
csvget "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment