0

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

1
  • Please read the description of tags you apply, you choice clearly shows you didn't. Also, as a new user here, take the tour and read How to Ask, in case you haven't already. Commented Aug 21, 2019 at 6:45

2 Answers 2

1
$ 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:
Sign up to request clarification or add additional context in comments.

2 Comments

There is a spacing problem with all expect the two first, change to -F": " and add a space after Size/Freq.. like this "Size%d: %s\n" to fix it. An idea for OP is to use n instead of 5 on your solution. It will then only print the number of field needed.
@Jotne I almost put a space before the colon on the Size lines to better match OP's desired output (and maybe indent Size4...). And he specifically said he wanted the extras for a total of 5...
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.