如何通过多条件判断计算两列比值并输出到不同文件
问题描述
假设存在以下数据(分隔符为单个空格,为便于阅读此处增加了空格):
col1 col2 col3 col4 col5 col6 col7 col8 col9 col10 1 P 0 0 1500 15000 0.5 0.0 200 name1 2 P 0 0 400 5000 0.7 0.2 150 name2 3 R 0 0 2000 2000 0.4 0.1 250 name3 4 R 0 0 5000 10000 0.2 0.3 600 name4 5 P 0 0 0 0 0.0 0.0 150 name5 6 R 0 0 6000 10000 0.1 0.0 120 name6 7 P 0 0 8 60 0.9 0.4 180 name7
期望按以下规则输出到不同文件:
- file1:当
col6 / col5 ≥8时 - file2:当
col6 / col5在1到6之间时 - file3:当
col6 / col5为零或出现除零错误时 - file4:当不满足上述所有条件(即比值在6.00000...1到7.9999...之间)时
尝试过以下代码,但仅能区分零值、小于10或大于10的情况:
awk 'NR!=1{printf "ratio for %s is %s.\n", $10, $6==0?"ZeroDivision":($6/$5>1)?$($6/$5):($6/$5)}' < /root/test_file
优先希望输出到多个文件,单个文件也可接受。
解决方案
使用以下awk脚本可以实现需求,将结果分别输出到指定文件:
NR != 1 { # 处理除零或比值为0的情况 if ($5 == 0 || $6 == 0) { print "ratio for " $10 " is Zero" > "file3" } else { ratio = $6 / $5 # 按比值区间分文件输出 if (ratio >= 8) { print "ratio for " $10 " is " ratio "." > "file1" } else if (ratio >= 1 && ratio <= 6) { print "ratio for " $10 " is " ratio "." > "file2" } else { print "ratio for " $10 " is " ratio "." > "file4" } } } # 关闭所有打开的文件,避免资源泄漏 END { close("file1") close("file2") close("file3") close("file4") }
脚本说明
- 跳过表头:
NR != 1表示只处理数据行,跳过第一行的表头。 - 异常处理:先判断
$5(分母)或$6(分子)为0的情况,直接输出到file3。 - 比值计算与分支:计算
ratio = $6 / $5后,按以下逻辑分配输出:- 比值≥8 → file1
- 比值在[1,6]区间 → file2
- 其他情况(6<ratio<8)→ file4
- 关闭文件:
END块中关闭所有文件,避免长时间运行时的资源占用问题。
输出结果
- file1内容:
ratio for name1 is 10.0. ratio for name2 is 12.5.
- file2内容:
ratio for name3 is 1.0. ratio for name4 is 2.0. ratio for name6 is 1.66667.
- file3内容:
ratio for name5 is Zero
- file4内容:
ratio for name7 is 7.5.
内容的提问来源于stack exchange,提问作者Saeed
相关产品推荐
相关产品推荐

