Unix - Combine All Rows into a Comma-Separated Single Row

Turning multiple lines into one comma separated line

Using paste command:

paste -d, -s file

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" 

Convert specified column in a multi-line string into single comma-separated line

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 merge every two lines into one from the command line?

awk:

awk 'NR%2{printf "%s ",$0;next;}1' yourFile

note, there is an empty line at the end of output.

sed:

sed 'N;s/\n/ /' yourFile

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 "," -

Join lines with similar first column

awk '{ A[$1] = A[$1] d[$1] $2; d[$1] = ","} 
END {for (i in A) print i, A[i]}' input.txt > output.txt

Explanation :
A[$1] = A[$1] d[$1] $2; - will set an associated array with index $1 and value A[$1] d[$1] $2. Initially it will be equal to $2 because A[$1] and d[$1] are not defined. d[$1] stores output delimiter "," .

END block prints the array index(unique 1st column ) and elements("," separated string) in a loop.

linux, Comma Separated Cells to Rows Preserve/Aggregate Column

cat > data << EOF
1 Cat1 a,b,c
2 Cat2 d
3 Cat3 e
4 Cat4 f,g
EOF

set -f # turn off globbing
IFS=, # prepare for comma-separated data
while IFS=$'\t' read C1 C2 C3; do # split columns at tabs
for X in $C3; do # split C3 at commas (due to IFS)
printf '%s\t%s\t%s\n' "$C1" "$C2" "$X"
done
done < data

arranging pairs of rows in to single row

This should do it:

awk 'NR%2==1 {line=$0; next} {printf("%-20s%-4s%s\n", line, $2, $3)}' file

This assumes that the lines appear in pairs with the same first field, as you've shown, and that there are no blank lines.



Related Topics



Leave a reply



Submit