Turning Multiple Lines into One Comma Separated Line

Turning multiple lines into one comma separated line

Using paste command:

paste -d, -s file

Turning multi-line string into single comma-separated

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/,$//)

How to concatenate multiple lines of output to one line?

Use tr '\n' ' ' to translate all newline characters to spaces:

$ grep pattern file | tr '\n' ' '

Note: grep reads files, cat concatenates files. Don't cat file | grep!

Edit:

tr can only handle single character translations. You could use awk to change the output record separator like:

$ grep pattern file | awk '{print}' ORS='" '

This would transform:

one
two
three

to:

one" two" three" 

How to convert multiple words in single line separated by comma in list of multiple lines


echo "your string" |tr \[ ' '|tr \] ' '|tr , \\n|awk '{$1=$1};1'

Explanation

  • echo "your string" prints your string, then piped to the next tr
  • tr \[ ' ' substitutes [ with an empty space
  • tr \] ' ' substitutes ] with an empty space
  • tr , \\n substitutes the comma with a newline
  • awk '{$1=$1};1' (taken from here) trims spaces

How to join multiple lines of file names into one with custom delimiter?

Similar to the very first option but omits the trailing delimiter

ls -1 | paste -sd "," -


Related Topics



Leave a reply



Submit