为什么 awk 不止一次打印这条线?

Pyt*_*ner 2 awk ldif

我有以下 ldif:

dn: cn=Robert Smith,ou=people,dc=example,dc=com
objectclass: inetOrgPerson
cn: Robert Smith
cn: Robert J Smith
cn: bob  smith
sn: smith
uid: rjsmith
userpassword: rJsmitH
carlicense: HISCAR 123
homephone: 555-111-2222
mail: r.smith@example.com
alias: rsmith@example.com
alias: bob.smith@example.com
description: nice hair
ou: Human Resources

dn: cn=John Doe,ou=people,dc=example,dc=com
objectclass: inetOrgPerson
cn: John Doe
cn: John Walker Doe
cn: Johnny
sn: Doe
uid: jdoe
userpassword: topsecret
carlicense: AKAHH 123
homephone: 123-458-362
mail: j.doe@example.com
alias: jdoe@example.com
alias: john.doe@example.com
description: cool guy
ou: Sales
Run Code Online (Sandbox Code Playgroud)

现在我正在针对它运行 awk 命令:

awk '/^mail:/ { mail = $2 }; {print mail };' ldif
Run Code Online (Sandbox Code Playgroud)

预期的结果是:

r.smith@example.com
j.doe@example.com
Run Code Online (Sandbox Code Playgroud)

实际结果是:

r.smith@example.com
r.smith@example.com
r.smith@example.com
r.smith@example.com
r.smith@example.com
r.smith@example.com
r.smith@example.com
r.smith@example.com
r.smith@example.com
r.smith@example.com
r.smith@example.com
r.smith@example.com
r.smith@example.com
r.smith@example.com
r.smith@example.com
r.smith@example.com
j.doe@example.com
j.doe@example.com
j.doe@example.com
j.doe@example.com
j.doe@example.com
Run Code Online (Sandbox Code Playgroud)

我真的不明白为什么 awk 多次给出这个输出。如果有人能向我解释它,我将不胜感激,因为我是 awk 的新手并且以前没有使用过它。我已经咨询了手册页和谷歌,但我想我在那里寻找错误的东西......

编辑:我知道 awk 按行处理文本流。我想我的“打印”只是打印输出,就像我的 ldif 文件中的行一样。但是我怎样才能防止 awk 这样做呢?我只想打印每个结果一次..

Den*_*nis 5

该条件/^mail:/不会影响后面的所有指令,只会影响第一个 ( mail = $2)指令。

结果,第二条指令 ( print mail)对每一行执行。

这就是为什么在输出的开头实际上有一些空行(mail尚未设置)。

这些中的任何一个都可以工作:

awk '/^mail:/ { { mail=$2 }; {print mail } };' ldif

awk '/^mail:/ { mail=$2; print mail };' ldif
Run Code Online (Sandbox Code Playgroud)

就个人而言,我更喜欢:

awk '/^mail:/ { print $2 }' ldif
Run Code Online (Sandbox Code Playgroud)