【问题标题】:How to compare number of lines of two files using Awk如何使用 Awk 比较两个文件的行数
【发布时间】:2015-02-11 10:42:43
【问题描述】:

我是 awk 新手,需要比较两个文件的行数。 脚本应返回 true,

if lines(f1) == (lines(f2)+1)

否则为假。我该怎么做?

最好的问候

【问题讨论】:

标签: awk text-processing line-count


【解决方案1】:

如果必须是awk:

awk 'NR==FNR{x++} END{ if(x!=FNR){exit 1} }' file1 file2

变量x 递增并包含file1 的行数,FNR 包含file2 的行数。最后,比较两者,脚本退出 0 或 1。

看一个例子:

user@host:~$ awk 'NR==FNR{x++} END{ if(x!=FNR){exit 1} }' shortfile longfile
user@host:~$ echo $?
1
user@host:~$ awk 'NR==FNR{x++} END{ if(x!=FNR){exit 1} }' samefile samefile
user@host:~$ echo $?
0

【讨论】:

  • :-) 非常简洁 - 投票。其实awk自然会以状态0退出,所以如果你倒置逻辑以状态1退出,你可以省略exit 0
  • 你甚至可以只做END{exit (x!=FNR)},但也许这太模糊了。
  • 我认为所需的功能是当一个文件比另一个文件包含多行时返回 1,而不是当两个文件包含相同数量的行时,不是吗?
【解决方案2】:

这样的东西应该适合你的目的:

 [ 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 $]

实际上,我想我应该在给你答案之前要求你投入更多的努力。我暂时先放着,但下次我不会再犯同样的错误了。

【讨论】:

    猜你喜欢
    • 2017-01-31
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 2017-07-25
    • 2014-10-12
    • 2012-01-01
    相关资源
    最近更新 更多