开发者

AWK If/ElseConditional Problem

开发者 https://www.devze.com 2022-12-26 17:46 出处:网络
I have a data that looks like this: foo fooscaffold_71 4845 6422 4845 bar barscaffold_7-1 14689 16310 16310

I have a 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 to process the above lines where I just want to print column 1,2,3, 7 and one more column after 7th. But with condition when printing column 7 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 it doesn't achieve the desired result like this?

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

Note that the arithmetic (e.g. $7-end or end+$7) is a must. So we can't 开发者_JAVA百科just swap column from input file. Furthermore this AWK will be inside a bash script.


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've never used braces within braces and prefer the semi-colon separators for this purpose. I'm pretty certain the else clause is bound only to {end=$6-$5} in your example, not to both the braced entries. In that case, {print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $7-end "\t" $7} will be executed for all lines.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消