I have a file with data like:

1,2,3 4,5,6 7,8,9 12,22,0

There are 4 columns I want to make a table with 4 columns say a,b,c,d, such that column a has value from 1st column, column b has that corrosponding value from column 2nd, and so on..

In above example the columns will be like:

a   b   c   d
1   4   7   12
2   5   8   22
3   6   9   0

Also the no. of entries in column for a particular line will be same. However these entries can be different for different lines, e.g. some line can have only 1 comma separated entry for each column, some can have even 10.

  • Is the space positioning in your original line intentional or just for the purpose of the presentation? – deimos Jun 18 '19 at 9:12
  • There is just 1 space between each column. – Prvt_Yadav Jun 18 '19 at 9:14
  • In that case you can split the sets of numbers into arrays named a, b, c and d and then just print the members of the array line by line. Granted your space/comma positiong is the same, you can use them as delimeters. – deimos Jun 18 '19 at 9:23

It's not really clear how you expect the columns to be named (either user input, either predefined name for every column to use, either some other way around).

Just to split string into columns you can with sed:

echo 1,2,3 4,5,6 7,8,9 12,22,0 | sed -n 'h;:a;g;s/,[^ ]*//gp;g;s/^[^, ]*,//;s/ [^,]*,/ /g;h;ta;p'

Here sed copies entire string to buffer (h), iterates through the line in cycle (:a..ta) where it gets copied string from buffer (g), get the first number from each part (first s) and prints it (p), then retrieves untouched string again, removes from it first number (second and third s) and puts modified string back to buffer (h). This continues while we have , in string. Once it's gone, we just print whatever is left with p.

  • Thanks it is working. But can you suggest me some good resource to study about grep labels, address ranges. – Prvt_Yadav Jun 18 '19 at 10:22
  • 1
    @Prvt_Yadv check this one: grymoire.com/Unix/Sed.html – rush Jun 18 '19 at 10:25

You can accomplish the task required as:

 $ sed -Ee '
     s/^/ /;y/ /\n/
        s/(\n.*)\n([^,]*),/\2 \1 /
     s/(.*) \n([^,]*),/\2 \1\n/
 ' inp

The recipe followed is to fashion the row to be printed by picking the leading column elements from each column.

Another way could be to split the columns into an array based in split on comma. Then shift out the leading elements till we run out of elements in any of the sub arrays, coz per line, their number are the same.

 $ perl -lane '$,=" ";
    my @A = map { [split /,/] } @F;
    print map { shift @$_ } @A while @{$A[0]};
 ' inp 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.