我是awk的新手,需要比较两个文件的行数。 该脚本将返回true,如何比较使用awk的两个文件的行数
if lines(f1) == (lines(f2)+1)
否则为false。我怎样才能做到这一点?
问候
我是awk的新手,需要比较两个文件的行数。 该脚本将返回true,如何比较使用awk的两个文件的行数
if lines(f1) == (lines(f2)+1)
否则为false。我怎样才能做到这一点?
问候
如果它必须是awk
:
awk 'NR==FNR{x++} END{ if(x!=FNR){exit 1} }' file1 file2
的varibale x
递增,并包含file1
线的数量和FNR包含file2
数量。最后,两者进行比较和脚本退出0或1
看到一个例子:
[email protected]:~$ awk 'NR==FNR{x++} END{ if(x!=FNR){exit 1} }' shortfile longfile
[email protected]:~$ echo $?
1
[email protected]:~$ awk 'NR==FNR{x++} END{ if(x!=FNR){exit 1} }' samefile samefile
[email protected]:~$ echo $?
0
:-)非常简洁 - 有投票权。实际上,'awk'自然会退出状态为零,所以如果你反转逻辑并退出状态1,你可以省略'exit 0'。 – 2015-02-11 13:07:13
@MarkSetchell啊,谢谢goot point – chaos 2015-02-11 13:09:41
你甚至可以做'END {exit(x!= FNR)}'但也许这太混乱了。 – 2015-02-11 21:07:14
像这样的东西应该根据自己的意图:
[ oele3110 $] cat line_compare.awk
#!/usr/bin/gawk -f
NR==FNR{
n_file1++;
}
NR!=FNR{
n_file2++;
}
END{
n_file2++;
if(n_file1==n_file2){exit(1);}
}
[ oele3110 $] cat f1
1
1
1
1
1
1
[ oele3110 $] cat f2
1
1
1
1
1
[ oele3110 $] cat f3
1
1
1
1
1
[ oele3110 $]
[ oele3110 $] wc -l f*
6 f1
5 f2
5 f3
16 total
[ oele3110 $] ./line_compare.awk f1 f2
[ oele3110 $] echo $?
1
[ oele3110 $] ./line_compare.awk f2 f3
[ oele3110 $] echo $?
0
[ oele3110 $]
其实,我觉得我应该问你给你答案之前投入更多的精力。我现在就离开它,但下次我不会犯同样的错误。
什么你试过吗? – 2015-02-11 10:43:24
通常情况下你会使用'wc -l'来计算文件中的行数......如果没有,请看看Ed的答案,看看如何处理2个文件http://stackoverflow.com/questions/21280959/using -awk-to-process-two-different-files-consecutively – 2015-02-11 10:51:44