Newline-Separated List to Comma-Separated List
Convert a newline-separated list into a single-line comma-separated list with quoted entries:
$EXEC_STUFF | sed 's/^\\|$/"/g' | paste -sd, -How it works:
sed 's/^\\|$/"/g'— wraps each line in double quotes (^= start,$= end)paste -sd, -— serial merge (-s) using,as the delimiter (-d), reading from stdin (-)
Example:
$ printf 'foo\nbar\nbaz\n' | sed 's/^\\|$/"/g' | paste -sd, -
"foo","bar","baz"
Platform note: On GNU/Linux (coreutils), the trailing - can be omitted. On macOS and other POSIX systems, include the - to read from stdin.
DOS line endings: If the input has \r\n line endings, strip the \r first:
sed 's/\r//;s/^\\|$/"/g' | paste -sd, -Comma+space separator: To get "foo", "bar", "baz" instead, use a two-step paste pipeline (see the raw source for the pure-paste approach) or switch to awk:
awk 'BEGIN { ORS="" } { print p"\047"$0"\047"; p=", " } END { print "\n" }' file.txtThe paste approach is notably fast — the kernel’s pipe handling makes it competitive with compiled tools for this task.
Related
- sed-single-line-find-replace — sed one-liner patterns
- bash-scripting — general shell text processing