为什么这个awk脚本看不到shell变量? [英] Why doesn't this awk script see the shell variable?

查看:138
本文介绍了为什么这个awk脚本看不到shell变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉我为什么该程序无法正常工作??帮我改善它.

Please tell me why this program is not working?? help me improve it.

for i in $(seq 2 30); do awk '{if ($i < 0.05) print $1,$i}' test.txt > phen_$i.txt; done

文件test.txt如下所示:

File test.txt looks like following:

name    phen1   phen2
rs549   0.02    0.02
rs699   0.03    0.03
rs701   1   1
rs751   0.449   0.449
rs884   1   1
rs923   0.9775  0.02
rs970   0.9836  0.03
rs1085  0.0001  0.99
rs1220  0.9316  0.9316

输出文件应该是两个不同的文件,即phen_2.txt和phen_3.txt,分别包含col1和col2以及col1和col3(根据if条件).

output file are expected to be two different files namely phen_2.txt and phen_3.txt containing col1 and col2, and col1 and col3 respectively according to if condition.

phen_2.txt的预期结果:

expected outcome for phen_2.txt:

rs549 0.02
rs699 0.03
rs1085 0.0001

phen_3.txt的预期结果:

expected outcome for phen_3.txt:

rs549 0.02
rs699 0.03
rs923 0.02
rs970 0.03

请帮助!

推荐答案

for ((i = 2; i <= 30; i++)); do awk -v i="$i" '$i < 0.05 {print $1, $i}' test.txt > "phen_$i.txt"; done

使用变量传递(-v)将Shell变量获取到AWK脚本中.

Use variable passing (-v) to get the shell variable into the AWK script.

您不需要seq.

修复了我一些过分的错误和严重的错误.

Fixed some overzealous and bad errors on my part.

以下是您可以在AWK中完全完成相同操作的方法:

Here's how you can do the same thing completely within AWK:

awk '{for (i = 2; i <= 30; i++) {if ($i < 0.05) {print $1, $i > "phen_" i ".txt"}}}' test.txt

此操作仅一次遍历输入文件,但会在每行输入中循环遍历一组输出文件. Shell版本重复读取输入文件,但一次写入每个输出文件.

This only goes through the input file once, but it cycles through the set of output files for each line of input. The shell version reads the input file repeatedly, but writes to each output file once.

这篇关于为什么这个awk脚本看不到shell变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆