foondar
foondar

Reputation: 45

Converting comma separated values into a list using shell

I have a file which looks like this:

Size: 20,30,40
Frequency: 60,70,80

I tried using sed where I replace the , with a new line and text but then that doesn't give me my desired output

sed 's/,/\nSize:/g' infile > outfile

I expect the output to be in a list format like the following manner (each in a new line ):

Size1 :20 
Frequency1: 60 
Size2 :30
Frequency2:70 
Size3 :40
Frequency3:80
 Size4 :
Frequency4: 
Size5 :
Frequency5:

I need two extra columns as some files can have 5 sizes

Upvotes: 0

Views: 92

Answers (2)

Jotne
Jotne

Reputation: 41456

A more generic solution based how Shawn's post. It stores line name in array s, so it will work with any number of line with data and any number of fields.

awk -F": " '{
    n=split($2,a,",");
    s[$1]++;
    for(i=1;i<=n;i++)
        v[$1,i]=a[i]} 
END {
    for(i=1;i<=n;i++) {
        for (j in s) 
            printf("%s%d: %s\n",j,i,v[j,i])
        }
    }' file

Frequency1: 60
Size1: 20
Frequency2: 70
Size2: 30
Frequency3: 80
Size3: 40

Upvotes: 0

Shawn
Shawn

Reputation: 52374

$ awk -F: '{ n = split($2, nums, /,/); for (i = 1; i <= n; i++) v[$1,i] = nums[i] }
           END { for (i = 1; i <= 5; i++) {
                   printf("Size%d:%s\n", i, v["Size",i])
                   printf("Frequency%d:%s\n", i, v["Frequency",i])
                 }
           }' input.txt
Size1: 20
Frequency1: 60
Size2:30
Frequency2:70
Size3:40
Frequency3:80
Size4:
Frequency4:
Size5:
Frequency5:

Upvotes: 1

Related Questions