Skip to content

Instantly share code, notes, and snippets.

@Saruspete
Created February 18, 2021 17:49
Show Gist options
  • Save Saruspete/e7619a5947021b9d311cdaefcb53a6a4 to your computer and use it in GitHub Desktop.
Save Saruspete/e7619a5947021b9d311cdaefcb53a6a4 to your computer and use it in GitHub Desktop.
Pure bash function to convert a list of args into CSV
function args2csv {
typeset -a fields=("$@")
# Escape existing quotes
fields=("${fields[@]//\"/\"\"}");
# Add " before and after fields
fields=("${fields[@]/#/\"}")
fields=("${fields[@]/%/\"}")
# Finally echo with , as separator
typeset IFS=','
echo "${fields[*]}"
}
# hello world "hi there" "I'm good" 'quoting " quote' "" "howdy,goody"
# should give:
# "hello","world","hi there","I'm good","quoting "" quote","","howdy,goody"
args2csv "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment