Join lines of output with commas

 · 1 min · torgeir

Sometimes you have multiple values separated by spaces, but you need them on a single line, separated by commas.

Terminal Paste

The paste command on linux, or gpaste on macos (because the macos one is a bit different), can join output from multiple lines into one, specifying the deilimiter you want.

echo "that\nwas\nhandy" | gpaste -s -d ","
that,was,handy

You could use this to extract a list of PIDs matching a criteria, if another command needs them as a comma separated list

sleep 10 & ; sleep 10 &
[1] 45035
[2] 45036

This lists processes matching sleep, disregarding the grep command it self, and prints the first column, interleaving , between each line of output.

ps x \
  | grep sleep \
  | grep -v grep \
  | awk '{print $1}' \
  | gpaste -s -d,
45035,45036