gpt4 book ai didi

awk:如何在 ENDFILE 中找到 "nextfile"?

转载 作者:行者123 更新时间:2023-12-03 23:42:45 26 4
gpt4 key购买 nike

请参阅“GNU Awk 用户指南”

The next statement (see section The next Statement) is not allowed inside either a BEGINFILE or an ENDFILE rule. The nextfile statement is allowed only inside a BEGINFILE rule, not inside an ENDFILE rule.


我在 BEGINFILE 中测试了“nextfile”:
即使nextfile写在BEGINFILE中,ENDFILE中对应的文件也会被执行
我想知道如何跳过 BEGINFILE 中“nextfile”的"file"

最佳答案

如果您的问题是“我们可以在 ENDFILE 部分中使用 nextfile 吗”那么简短的回答是否定的,我们不能使用它。
这是一个例子:

  • 使用 nextfileBEGINFILE部分:假设我们有 2 个名为 file1 和 file2 的 Input_files。
    让我们跑 nextfileBEGINFILE规则。
  • awk 'BEGINFILE{print FILENAME;nextfile} 1' file1 file2
    file1
    file2
    我们可以看到它在其中打印 Input_file 名称,而不是打印文件的内容,这意味着它工作正常。
  • 使用 nextfileENDFILE区块:现在让我们运行 nextfileENDFILE部分,看看会发生什么。
  • awk '1;ENDFILE{nextfile;print "bla bla"}' file1 file2
    awk: cmd. line:1: error: `nextfile' used in ENDFILE action
    正如您在上面看到的那样,它给出了一个错误。为什么会发生这种情况,因为 ENDFILEEND块总是在 Input_file(s) 的所有记录执行完成后执行,所以如果你想跳到下一个 Input_file 那么你可以在 BEGINFILE 中使用它或 BEGIN部分或在 main block 中使用它如果您想匹配特定条件,然后跳转到下一个 Input_file。

    如何跳过ENDFILE特定 Input_file 的部分:如果您有 ENDFILE然后在每个 Input_file 的记录读取上声明,然后跳过特定的 Input_file 我们可以使用这样的条件:
    awk '1;ENDFILE{if(FILENAME!="file2"){print FILENAME}}' file1 file2
    输出如下。
    bla bla bla file1 contents here.....
    file1
    bla bnla bla file2 contents here....
    基本上它的 Input_file1 和 Input_file2 的打印内容但是因为在 ENDFILE 中提到了一个条件在输出中阻止其 NOT 打印 file2 名称,因此阻止了在 ENDFILE 中执行的语句堵在这里。

    nextfile的理想用途在 BEGINFILE区块:如果我们使用 nextfileBEGINFILE阻塞然后它肯定不会打印该特定 Input_file 的任何记录,为什么因为 BEGINFILE当我们提到 nextfile 时,块的语句在从 Input_file 读取记录之前执行它不会开始读取记录过程,只会跳转到下一个 Input_file。
    那么什么时候使用nextfileBEGINFILE阻止?:恕我直言,最好的用例之一是当我们想要处理多个 Input_file(s) 并想要处理每个 Input_file 的 header 时(例如--> 仅打印 header 或特定文件的消息,并且不处理该 Input_file 的记录)。或第二种情况,我可以考虑在执行该 Input_file 的记录之前是否需要进行任何处理。

    关于awk:如何在 ENDFILE 中找到 "nextfile"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64816132/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com