line34
Coding, Scripting, Administration

Convert multiple lines to comma separated list

To concatenate multiple lines of text and separate them by commas, I use this sed script:

sed -n '$!{s/.*/\0,/;H};${H;x;s/\n//gp}'

This way you can e.g. use the output of a ps command as an argument for top to only display java and python processes:

top -p `ps -C python,java -o pid --no-headers | sed -n '$!{s/.*/\0,/;H};${H;x;s/\n//gp}'`

Thanks goes to bakunin, whose script in a thread at unix.com got me started.

9th November 2014Filed under: bash   sed