Turning multi-line string into single comma-separated Turning multi-line string into single comma-separated shell shell

Turning multi-line string into single comma-separated


Clean and simple:

awk '{print $2}' file.txt | paste -s -d, -


You can use awk and sed:

awk -vORS=, '{ print $2 }' file.txt | sed 's/,$/\n/'

Or if you want to use a pipe:

echo "data" | awk -vORS=, '{ print $2 }' | sed 's/,$/\n/'

To break it down:

  • awk is great at handling data broken down into fields
  • -vORS=, sets the "output record separator" to ,, which is what you wanted
  • { print $2 } tells awk to print the second field for every record (line)
  • file.txt is your filename
  • sed just gets rid of the trailing , and turns it into a newline (if you want no newline, you can do s/,$//)


cat data.txt | xargs | sed -e 's/ /, /g'