Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Created February 21, 2014 21:19
Show Gist options
  • Save coderofsalvation/9143744 to your computer and use it in GitHub Desktop.
Save coderofsalvation/9143744 to your computer and use it in GitHub Desktop.
transforms every x number of lines to one commaseperated line
# merges x number of lines to one commaseperated line
# usage: echo -e "jan\ncold\nrain\njune\nhot\dry\n" | lines_to_csv ',' 'a,b,c'
# will output:
# "jan","cold","rain"
# "june","hot","dry"
lines_to_csv(){
lines="$(cat -)"; delimiter="$1"; columns="$2";
outputline=""
ncolumns="$( echo "$columns" | grep -o "$delimiter" | wc -l)";
i=0; echo "$lines" | while read line; do
[[ "${#outputline}" > 0 ]] && outputline="$outputline""$delimiter\"$line\"" || outputline="\"$line\""
((i++)); (( i > ncolumns )) && echo "$outputline" && i=0 && outputline=""
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment