Search code examples
unixdataformat

How to format the data of a file in Unix?


I have some data in this form (3 columns) stored in the variable ABC:

d1  d2 d3 
d4 d5 d6 
d7 d8 d9 
d10 

and I would like to format it in this form (4 columns):

d1 d2 d3 d4 
d5 d6 d7 d8
d9 d10

I've tried something like this:

printf "%8.3e %8.3e %8.3e %8.3e\n" "${ABC}"

but it doesn't work. Can anyone see where the problem is?


Solution

  • So you have a file with a content like this:

    d1 d2 d3
    d4 d5 d6
    d7 d8 d9
    d10
    

    and you want to convert it into

    d1 d2 d3 d4
    d5 d6 d7 d8
    d9 d10
    

    That is, convert it from 3 columns per line into 4.

    For this you can use xargs like:

    xargs -n 4 < file
    

    Or, if the data is in a variable:

    xargs -n 4 <<< "$variable"
    

    From man xargs

    -n max-args, --max-args=max-args

    Use at most max-args arguments per command line.

    Test

    $ cat a
    1 2 3
    4 5 6
    7 8 9
    10
    $ xargs -n 4 < a
    1 2 3 4
    5 6 7 8
    9 10