【发布时间】:2018-08-10 13:59:26
【问题描述】:
我想灵活地将两个小 awk 的输出打印到 bash 管道,它们使用变量(它们最初工作)。我最初认为我可以将整个命令存储为变量本身,但对于一个它不起作用并且显然 (store awk command in a variable of bash script) 这不是一个好主意。所以我写了两个函数,但我在“完成”附近得到了一个“意外令牌”,但它的格式如上面的链接所示。
我的错误在哪里?
for coverage_file in */*.cov
do
#gene_count=$(awk '{print $5}' $coverage_file |sort | uniq -c | wc -l) #this is apparently not a good idea
#contig_count=$(awk '{print $1}' $coverage_file |sort | uniq -c | wc -l) #this is apparently not a good idea
cmd_gene() { awk '{print $5}' $coverage_file |sort | uniq -c | wc -l }
cmd_contig() { awk '{print $1}' $coverage_file |sort | uniq -c | wc -l }
cmd_gene $coverage_file
cmd_contig $coverage_file
#print "we found", $gene_count, "genes on ",$contig_count" contigs
done
cov 文件如下所示:
k141_85332.3 4119 19 A5 phnM_031
k141_85332.3 4119 19 A5 phnM_031
k141_85332.3 4119 28 A1 phnM_031
k141_85332.3 4119 28 A1 phnM_031
k141_85332.3 4119 8 A2 phnM_031
k141_85332.3 4119 8 A2 phnM_031
k141_88684 267 5 B10 phnM_032
k141_88684 268 5 B10 phnM_032
k141_88684 269 5 B10 phnM_032
k141_88684 270 5 B10 phnM_032
k141_88684 271 5 B10 phnM_032
k141_88684 272 5 B10 phnM_032
编辑:这包括接受的答案 + 一种可能的方式来清楚地打印它:
#!/bin/bash
#define variables
gene="phnM"
threshold="5"
#define functions
cmd_gene() { awk '{print $5}' $1 |sort | uniq -c | wc -l ; } #semicolon is important here!
cmd_contig() { awk '{print $1}' $1 |sort | uniq -c | wc -l ; } #semicolon is important here!
#loop over files and print results (would be prettier with printf)
for coverage_file in */*.cov
do
echo $gene" was found" $(cmd_gene "$coverage_file") "times on" $(cmd_contig "$coverage_file")" contigs with minimum coverage of" $threshold in $coverage_file
done
输出:
phnM was found 67 times on 65 contigs with minimum coverage of 5 in phnm/test.cov
phnM was found 3 times on 2 contigs with minimum coverage of 5 in test/test.cov
【问题讨论】:
-
出现了意外的令牌错误,因为当您定义一个函数时,
}必须在它自己的行上或前面有;。例如:cmd_contig() { awk '{print $1}' $coverage_file |sort | uniq -c | wc -l; } -
嗯,很尴尬 ;-) 谢谢。你想把它作为答案发布吗?
-
还不算尴尬;当然,我会添加作为答案,谢谢。
标签: function variables awk printing