bashshellnetapp

bash script to read table line by line


Sample Input: (tab separated values in table format)

Vserver   Volume       Aggregate    State      Type       Size  Available Used%
--------- ------------ ------------ ---------- ---- ---------- ---------- -----
vs1       vol1         aggr1        online     RW          2GB      1.9GB    5%

vs1       vol1_dr      aggr0_dp     online     DP        200GB    160.0GB   20%

vs1       vol2         aggr0        online     RW        150GB    110.3GB   26%

vs1       vol2_dr      aggr0_dp     online     DP        150GB    110.3GB   26%

vs1       vol3         aggr1        online     RW        150GB    120.0GB   20%

I've a task to find the volumes under an aggregate which has breached threshold so that they can be moved to a different aggregate. Need your help to read the above table line by line, capture volume associated with a specific aggregate name (which will passed as an argument) and add the size of the volume to variable (say total). The next lines should be read till the variable, total is less than or equal to the size that should be moved (again which will passed as an argument)

Expected output if <aggr1> and <152GB> are passed as arguments

vol1         aggr1        2GB      
vol3         aggr1        150GB   

Solution

  • You want to read the file line by line, so you can use awk. You give arguments with the syntax -v aggr=<aggr>. You will enter that on command line:

    awk -f script.awk -v aggr=aggr1 -v total=152 tabfile
    

    here is an awk script:

    BEGIN {
        if ( (aggr == "") || (total == 0.) )  {
            print "no <aggr> or no <total> arg\n" 
            print "usage: awk -f script.awk -v aggr=<aggr> -v total=<total> <file_data>"
            exit 1;}
        sum = 0;
    }   
    
    $0 ~ aggr {
        scurrent = $6;  sub("GB","", scurrent);
        sum += scurrent;
        if (sum <= total)   print  $2 "\t" $3 "\t" $6;
        else   exit 0;
    }
    

    The BEGIN block is interpreted once, at the beginning! Here you initialize sum variable and you check the presence of mandatory arguments. If they are missing, their value is null.

    The script will read the file line by line, and will process only lines containing aggr argument.

    Each column is referred thanks to $ and its NUM; your volume size is in the column $6.