我在第二栏中有大量的制表符分隔的文本文件,其中包含我感兴趣的分数:
test_score_1.txt
Title FRED Chemgauss4 File
24937 -6.111582 A
24972 -7.644171 A
26246 -8.551361 A
21453 -7.291059 A
test_score_2.txt
Title FRED Chemgauss4 File
14721 -7.322331 B
27280 -6.229842 B
21451 -8.407396 B
10035 -7.482369 B
10037 -7.706176 B
我想检查标题是否比我定义的数字小.
以下代码在脚本中定义了我的分数并起作用:
check_score_1
#!/bin/bash
find . -name 'test_score_*.txt' -type f -print0 |
while read -r -d $'\0' x; do
awk '{FS = "\t" ; if ($2 < -7.5) print $0}' "$x"
done
如果我尝试将像check_scores_2.sh这样的参数传递给awk,如check_score_2.sh所示为“ -7.5”,则这将返回两个文件中的所有条目.
check_scores_2.sh
#!/bin/bash
find . -name 'test_score_*.txt' -type f -print0 |
while read -r -d $'\0' x; do
awk '{FS = "\t" ; if ($2 < ARGV[1]) print $0}' "$x"
done
最后,check_scores_3.sh显示我实际上没有从命令行传递任何参数.
check_scores_3.sh
#!/bin/bash
find . -name 'test_score_*.txt' -type f -print0 |
while read -r -d $'\0' x; do
awk '{print ARGV[0] "\t" ARGV[1] "\t" ARGV[2]}' "$x"
done
$./check_score_3.sh“ -7.5”给出以下输出:
awk ./test_score_1.txt
awk ./test_score_1.txt
awk ./test_score_1.txt
awk ./test_score_1.txt
awk ./test_score_1.txt
awk ./test_score_2.txt
awk ./test_score_2.txt
awk ./test_score_2.txt
awk ./test_score_2.txt
awk ./test_score_2.txt
awk ./test_score_2.txt
我究竟做错了什么?
解决方法:
在您的shell脚本中,shellscript的第一个参数为$1.您可以将该值分配给awk变量,如下所示:
find . -name 'test_score_*.txt' -type f -exec awk -v a="$1" -F'\t' '$2 < a' {} +
讨论区
>您的print0 / while读取循环非常好.但是,find提供的-exec选项可以在不进行任何显式循环的情况下运行同一命令.
>可以选择将命令{if($2< -7.5)打印$0}简化为条件$2<. -7.5.这是因为条件的默认操作是print $0.
>请注意,引用$1和$2完全不相关.因为$1用双引号引起来,所以shell在awk命令开始运行之前用它代替. shell解释$1表示脚本的第一个参数.因为$2用单引号引起来,所以外壳程序将其保留下来,并由awk解释. Awk将其解释为当前记录的第二个字段.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。