简体   繁体   中英

transposing multiple columns in bash

demilited file like this

Input1 file1:45764
Input1 file1:878755
Input1 file1: 899787
Input2 file1: 45676
Input2 file1:769678
Input2 file1: 6454764

and I wish to convert them into

Input1 file1:45764, file1:878755, file1: 899787 
Input2 file1:45676, file1:769678, file1: 6454764 

Any guess? Thanks in advance

awk '{b[$1]=b[$1] $2$3"  "}END{for (i in b) print i,b[i]}' inputFile

will produce output as

Input1 file1:45764  file1:878755  file1:899787  
Input2 file1:45676  file1:769678  file1:6454764  

what it does?

{b[$1]=b[$1] $2$3" "} creates an array b appends the second and third column(since there was some spaces between file and value in your example). $2$3 into the array. The array is an associative array indexed by the Inputx where x is 1,2...

that is

b['Input1'] = 'file1:45764  file1:878755  file1:899787'

END block is excecuted at end of input file, input ,

for (i in b) print i,b[i]} prints the content of b array

And if you want those commas in the output, try

awk '{if(b[$1])b[$1] = b[$1]", "; b[$1] = b[$1] $2 $3}; END{for(i in b)print i, b[i]}'

or the slightly terser

awk '{b[$1]=b[$1](b[$1]?", ":"")$2$3}END{for(i in b)print i,b[i]}'

output

Input1 file1:45764, file1:878755, file1:899787
Input2 file1:45676, file1:769678, file1:6454764

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM