AWK If / ElseConditional Problem

I have data that looks like this:

foo foo      scaffold_7      1 4845 6422 4845
bar bar      scaffold_7      -1 14689 16310 16310

      

What I want to do is process the above lines where I just want to print column 1,2,3,7 and one more column after the 7th. But with a condition when printing column 7 and onwards.

Below is my awk script:

awk '{ 
        if ($4=="+") { {end=$6-$5}{print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $7 "\t" end+$7} } 
        else 
            {end=$6-$5}{print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $7-end "\t" $7} 
    }'  

      

But why doesn't he achieve the desired result?

foo foo    scaffold_7      1       4845    6422
bar bar   scaffold_7      -1      14689   16310

      

Note that arithmetic (such as $7-end

or end+$7

) is required. Thus, we cannot simply replace the column from the input file. Also, this AWK will be inside the bash script.

+2


source to share


2 answers


Try:

awk 'BEGIN {OFS = "\t"} { 
    end = $6 - $5
    if ($4 >= 0) {
        print $1, $2, $3, $4, $7, end + $7
    } else {
        print $1, $2, $3, $4, $7 - end, $7
    }
}'

      



I have never used curly braces within curly braces and prefer two colons delimiters for this purpose. I'm pretty sure the else clause is only bound to {end=$6-$5}

in your example and not to the copied elements. In this case, it {print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $7-end "\t" $7}

will be executed for all lines.

+3


source


awk '{end=$6-$5}
$4>0{ $0=$1 "\t" $2 "\t" $3 "\t" $4 "\t" $7 "\t" end+$7 }
$4<=0{$0=$1 "\t" $2 "\t" $3 "\t" $4 "\t" $7-end "\t" $7 }1'  file

      



+3


source







All Articles