Home > OS >  subtraction of two columns from different rows
subtraction of two columns from different rows

Time:09-14

How do I subtract the value of column 2 of one row with the value of column 3 of the previous row and print the result in a new row in bash.

I tried with awk like this, but I miss the part to change the line

 awk '{a=$3; b=$2; c=a-b;print $0,c;}' input.bed

The input is:

NC_048323.1 21 29
----------------------
NC_048323.1 62 65
----------------------
NC_048323.1 128 179
--------------------
NC_048323.1     204     238
--------------------------
NC_048323.1     296     392
--------------------------
NC_048323.1     427     448
---------------------------
NC_048323.1     477     507
---------------------------

My desired output then is:

NC_048323.1     21      29    21
---------------------------------
NC_048323.1     62      65    33
---------------------------------
NC_048323.1     128     179   63
---------------------------------
NC_048323.1     204     238   25
---------------------------------
NC_048323.1     296     392   58
---------------------------------
NC_048323.1     427     448   35
---------------------------------
NC_048323.1     477     507   29
---------------------------------

CodePudding user response:

Maybe this litte awk helps, some explanation:

In the BEGIN section the field separator FS is set to space and the output field separator OFS is set to tab

If there is only one input line, print it

If there are three input lines, save the previous integer value of the 3rd and the integer values of the recent 2nd and 3rd columns, then print them out, delimited by the output filed separator, but: If there is an integer value in int_3rd_prev make the desired calculation otherwise print the value of the 2nd integer value

HTH

awk '
BEGIN { 
    FS=" "
    OFS="\t"
    }
NF == 1 {
    print $0
    }
NF == 3 {
    int_3rd_prev=int_3rd
    int_2nd=$2
    int_3rd=$3
    printf("%s%s=%s=%s=\n", $1, OFS, int_2nd, OFS, int_3rd, OFS, (int_3rd_prev == "" ? int_2nd : int_2nd - int_3rd_prev ))
    }' \
input.bed
  •  Tags:  
  • bash
  • Related