bash 带有嵌套 if else 的 awk
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15086683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
awk with nested if else
提问by Angelo
I have a tab delimited two column data. I want to get the third based on the condition applied on second column.
我有一个制表符分隔两列数据。我想根据应用于第二列的条件获得第三个。
if second column is not equal to zero it should print col 1 and 3 and ratio of col1/col2 if col two is zero and col one is more than 15 than it should print col 1 and col2 and the value in col1 (in col 3) else (when col1<=15 & col2 is 0) it should print col1 col2 and 0.
如果第二列不等于零,它应该打印第 1 列和第 3 列以及 col1/col2 的比率,如果第 2 列为零且第一个列大于 15,则它应该打印第 1 列和第 2 列以及 col1 中的值(在第 3 列中) ) 否则(当 col1<=15 & col2 为 0 时)它应该打印 col1 col2 和 0。
for example, for a file like this
例如,对于这样的文件
1 2
4 5
6 7
14 0
18 0
the output should be
输出应该是
1 2 0.5
4 5 0.8
6 7 0.85
14 0 0
18 0 18
What I have tried:
我尝试过的:
awk '{if (!=0) print "\t" "\t" /; elseif(>15) print "\t" "\t" ; else print "\t" "\t" }'<tags| head
Obviously I am doing something wrong, please help me in getting the above code right.
显然我做错了什么,请帮助我正确地获得上述代码。
Thank you
谢谢
回答by Kent
a funny but unreadable(maybe) :) one-liner:
一个有趣但不可读(也许):) 单行:
awk '{a=boolean? first : second
this means assign var a, if boolean true, using value first, otherwise use value second.
I set `awk '! { = >15 ? : 0 } { = / } 1' OFS='\t' CONVFMT='%.2g'
= ? FOO : BAR`
FOO part: FS FS /
BAR part: >15? FOO2 : BAR2
FOO2 part: FS FS
BAR2 part: FS FS "0"
finally, print 1 2 0.5
4 5 0.8
6 7 0.86
14 0 0
18 0 18
=?FSFS/:>15?FSFS:FSFS"0"}1' file
short explaination:
简短说明:
awk '{=>=15 && ==0?:<15 && ==0?0:/}1' your_file
Problem in your code
你的代码有问题
chang elseif-> else ifalso check $1with 15, not $2then your oneliner works too.
昌elseif- >else if还要检查$1与15不$2那么你oneliner工作过。
回答by Thor
Here's another alternative:
这是另一种选择:
awk '{if(!=0) =/; else if(>15) =; else =0}1' OFS='\t' file
Output:
输出:
awk '{=0} >15{=} {=/}1' OFS='\t' file
回答by Vijay
awk '{=?/:>15?:0}1' OFS='\t' file
回答by Scrutinizer
Slightly different way:
稍微不同的方式:
##代码##Determined by the order of the if clause:
由 if 子句的顺序决定:
##代码##or the cryptic version:
或神秘版本:
##代码##
