Search code examples
bashsedawkcsh

how to extract certain columns of a file and save them in new file


I have a file which contains lines of data in the following format:

a11 a12 a13 a14 a15
a21 a22 a23 a24 a25 
a31 a32 a33 a34 a35 
a41 a42 a43 a44 a45 
.
.
.

what I need is to save this data in a new file with the following format after performing some arithmetic on it:

a11 
a12*x1 a13/y1 z1*a15+d1
a21 
a22*x2 a23/y2 z2*a25+d2
a31 
a32*x3 a33/y3 z3*a35+d3
.
.
.
.

all the xi, yi, zi and di are float numbers. These numbers are stored ina second file having the format:

x1 y1 z1 d1
x2 y2 z2 d2
x3 y3 z3 d3
.
.
.

I really appreciate it if you could please guide with a csh or bash snippet on how this can be done.

Cheers


Solution

  • The script (I call it matmath):

    #!/usr/bin/awk -f
    BEGIN {
        factors = ARGV[1]
        ARGC--
    }
    {
        print $1
        getline line < factors
        split(line, f)
        print $2 * f[1], $3 / f[2], f[3] * $5 + f[4]
    }
    

    The data files:

    matrix:

    11 12 13 14 15
    21 22 23 24 25
    31 32 33 34 35
    41 42 43 44 45
    

    factors:

    1.1 1.2 1.3 1.4 1.5
    2.1 2.2 2.3 2.4 2.5
    3.1 3.2 3.3 3.4 3.5
    4.1 4.2 4.3 4.4 4.5
    

    Example run:

    $ chmod u+x matmath    # run once to set the script to be executable
    $ ./matmath factors matrix
    1.1
    1.32 1.08333 3.35
    2.1
    4.62 1.04545 8.15
    3.1
    9.92 1.03125 14.95
    4.1
    17.22 1.02381 23.75