什么是" NR == FNR"在awk?

时间:2015-09-09 14:09:40

标签: linux unix awk

我正在使用awk学习文件比较。

我找到了如下语法,

awk 'NR==FNR{a[$1];next}$1 in a{print $1}' file1 file2

我无法理解NR==FNR在这里有什么重要意义? 如果我尝试FNR==NR,那么我也得到相同的输出?

它到底是做什么的?

3 个答案:

答案 0 :(得分:31)

在awk手册中查找NRFNR,然后问自己以下示例中NR==FNR的条件是什么:

$ cat file1
a
b
c

$ cat file2
d
e

$ awk '{print FILENAME, NR, FNR, $0}' file1 file2
file1 1 1 a
file1 2 2 b
file1 3 3 c
file2 4 1 d
file2 5 2 e

答案 1 :(得分:10)

awk个内置变量。

NR - 它给出了处理的记录总数。

FNR - 它给出了每个输入文件的总记录数。

答案 2 :(得分:7)

假设您有文件a.txt和b.txt

java.lang.NoClassDefFoundError: com/jayway/jsonpath/Predicate
    at com.amazon.isp.execution.notifications.messageHandlers.CosmosNotificationsHandler$$anonfun$2.apply(CosmosNotificationsHandler.scala:164) ~[ScreeningExecutionEngineService-1.0.jar:?]
    at com.amazon.isp.execution.notifications.messageHandlers.CosmosNotificationsHandler$$anonfun$2.apply(CosmosNotificationsHandler.scala:153) ~[ScreeningExecutionEngineService-1.0.jar:?]
    at scala.util.Try$.apply(Try.scala:192) ~[scala-library.jar:?]
    at com.amazon.isp.execution.notifications.messageHandlers.CosmosNotificationsHandler.getEventType(CosmosNotificationsHandler.scala:153) ~[ScreeningExecutionEngineService-1.0.jar:?]
    at com.amazon.isp.execution.notifications.messageHandlers.CosmosNotificationsHandler.processMessage_aroundBody0(CosmosNotificationsHandler.scala:63) ~[ScreeningExecutionEngineService-1.0.jar:?]
    at com.amazon.isp.execution.notifications.messageHandlers.CosmosNotificationsHandler$AjcClosure1.run(CosmosNotificationsHandler.scala:1) ~[ScreeningExecutionEngineService-1.0.jar:?]
    at org.a

请记住 NR和FNR是awk内置变量。 NR - 提供处理的记录总数。 (在这种情况下都在a.txt和b.txt中) FNR - 给出每个输入文件的记录总数(记录在a.txt或b.txt中)

cat a.txt
a
b
c
d
1
3
5
cat b.txt
a
1
2
6
7

让Add" next"跳过与NR == FNR匹配的第一个

在b.txt和a.txt

awk 'NR==FNR{a[$0];}{if($0 in a)print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
a.txt 1 1 a
a.txt 2 2 b
a.txt 3 3 c
a.txt 4 4 d
a.txt 5 5 1
a.txt 6 6 3
a.txt 7 7 5
b.txt 8 1 a
b.txt 9 2 1

在b.txt中,但不在a.txt中

awk 'NR==FNR{a[$0];next}{if($0 in a)print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
b.txt 8 1 a
b.txt 9 2 1
相关问题