分页: 1 / 1

awk中变量的使用

发表于 : 2013-11-15 20:33
蒙毅酋长
这是awk的命令:

代码: 全选

awk '{if (index($8,"1")==4) {print $0 > "$prifx_chr1_tmp"}\
 else if (index($8,"2")==4) {print $0 > "$prifx_chr2_tmp"}\                  
 else if (index($8,"3")==4) {print $0 > "$prifx_chr3_tmp"}\
 else if (index($8,"4")==4) {print $0 > "$prifx_chr4_tmp"}\
 else if (index($8,"5")==4) {print $0 > "$prifx_chr5_tmp"}\
 else if (index($8,"6")==4) {print $0 > "$prifx_chr6_tmp"}\
 else if (index($8,"7")==4) {print $0 > "$prifx_chr7_tmp"}}' $1
其中

代码: 全选

print $0 > 
这个,生成的文件都是以$prifx开头的,原来是想按

代码: 全选

$prifx=09110
这样来的。想不成结果却是另一个样子,不知道这其中的问题是在哪呢?

代码: 全选

$1
是指一个文本文件。
谢谢大家

Re: awk中变量的使用

发表于 : 2013-11-16 12:05
lilydjwg
没太明白问题。不过,awk 里是不像 shell 那样扩展 $var 这种变量的。如果你的 shell 里设置了 prefix=09110 的话,在 awk 可以这么用:
[bash]
awk -vprefix=$prefix '{if (index($8,"1")==4) {print $0 > prefix"_chr1_tmp"}\
else if (index($8,"2")==4) {print $0 > prefix"_chr2_tmp"}\
else if (index($8,"3")==4) {print $0 > prefix"_chr3_tmp"}\
else if (index($8,"4")==4) {print $0 > prefix"_chr4_tmp"}\
else if (index($8,"5")==4) {print $0 > prefix"_chr5_tmp"}\
else if (index($8,"6")==4) {print $0 > prefix"_chr6_tmp"}\
else if (index($8,"7")==4) {print $0 > prefix"_chr7_tmp"}}' $1
[/bash]

不过感觉这个脚本写得好麻烦啊。

Re: awk中变量的使用

发表于 : 2013-12-22 22:49
sk1418
1, 看不到你的输入,不好多说。但是你这个脚本一定会有更简化的版本。

2. 如果要用shell 变量,要用-v 比如

代码: 全选

awk -v foo="$HOME" '{...code... ; print "my Home dir is:" foo}' input