bash GAWK 脚本 - 在 BEGIN 部​​分打印文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5442003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:40:45  来源:igfitidea点击:

GAWK Script - Print filename in BEGIN section

linuxbashshellawkgawk

提问by jonseager

I am writing a gawk script that begins

我正在写一个开始的 gawk 脚本

#!/bin/gawk -f
BEGIN { print FILENAME }

I am calling the file via ./script file1.htmlbut the script just returns nothing. Any ideas?

我通过调用文件,./script file1.html但脚本只返回任何内容。有任何想法吗?

回答by kurumi

you can use ARGV[1] instead of FILENAME if you really want to use it in BEGIN block

如果你真的想在 BEGIN 块中使用它,你可以使用 ARGV[1] 而不是 FILENAME

awk 'BEGIN{print ARGV[1]}' file

回答by Hai Vu

You can print the file name when encounter line 1:

您可以在遇到第 1 行时打印文件名:

FNR == 1

If you want to be less cryptic, easier to understand:

如果你想不那么神秘,更容易理解:

FNR == 1 {print}

UPDATE

更新

My first two solutions were incorrect. Thank you Dennis for pointing it out. His way is correct:

我的前两个解决方案是不正确的。谢谢丹尼斯指出。他的方法是正确的:

FNR == 1 {print FILENAME}

回答by JUST MY correct OPINION

Straight from the man page (slightly reformatted):

直接从手册页(稍微重新格式化):

FILENAME: The name of the current input file. If no files are specified on the command line, the value of FILENAME is “-”. However, FILENAME is undefined inside the BEGIN block (unless set by getline).

FILENAME:当前输入文件的名称。如果命令行没有指定文件,FILENAME 的值为“-”。但是, FILENAME 在 BEGIN 块内未定义(除非由 getline 设置)。

回答by Warren Wright

Building on Hai Vu's answer I suggest that if you only want the filename printed once per file it needs to be wrapped in a conditional.

以 Hai Vu 的回答为基础,我建议如果您只想为每个文件打印一次文件名,则需要将其包装在条件中。

if(FNR == 1) { print FILENAME };