Skip to content

Instantly share code, notes, and snippets.

@dualbus
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dualbus/9665803 to your computer and use it in GitHub Desktop.
Save dualbus/9665803 to your computer and use it in GitHub Desktop.
sed '/./!be;s/"/""/g;/[, \t"]/s/.*/"&"/;H;$!d;:e;x;s/\n//;s/\n/,/g'
/./! b exchange
# escape double quotes and fields
s/"/""/g
/[, \t"]/s/.*/"&"/
# append to Hold buffer and restart cycle if it's not the last line
H
$!d
:exchange
x
s/\n//
s/\n/,/g
#!/bin/sh
set -ux
unset script
trap 'rm -f "$script"' EXIT
script=$(mktemp)
oneliner() {
sed '/./!be;s/"/""/g;/[, \t"]/s/.*/"&"/;H;$!d;:e;x;s/\n//;s/\n/,/g'
}
script() {
sed -f "$script"
}
cat <<'eof' > "$script"
/./! b exchange
# escape double quotes and fields
s/"/""/g
/[, \t"]/s/.*/"&"/
# append to Hold buffer and restart cycle if it's not the last line
H
$!d
:exchange
x
s/\n//
s/\n/,/g
eof
for command in oneliner script; do
o=$("$command" <<eof
a b c
c d e
123
eof
)
[ "$o" = '"a b c","c d e"
123' ]; echo $?
o=$("$command" <<eof
1 2 3
eof
)
[ "$o" = '"1 2 3"' ]; echo $?
o=$("$command" <<eof
1, 2 3
eof
)
[ "$o" = '"1, 2 3"' ]; echo $?
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment