gpt4 book ai didi

awk - 如何在awk中跳过目录?

转载 作者:行者123 更新时间:2023-12-02 00:00:53 24 4
gpt4 key购买 nike

假设我有以下文件和目录结构:

$ tree
.
├── a
├── b
└── dir
└── c

1 directory, 3 files

也就是说,两个文件 ab 以及一个目录 dir,其中另一个文件 c 所在.

我想用 awk 处理所有文件(确切地说是 GNU Awk 4.1.1),所以我做了这样的事情:

$ gawk '{print FILENAME; nextfile}' * */*
a
b
awk: cmd. line:1: warning: command line argument `dir' is a directory: skipped
dir/c

一切都很好,但 * 也扩展到目录 dir 并且 awk 尝试处理它。

所以我想知道:是否有任何本地方法 awk 可以检查给定元素是否是文件,如果是,则跳过它?也就是说,不使用 system()

我通过调用 BEGINFILE 中的外部系统使其工作。 :

$ gawk 'BEGINFILE{print FILENAME; if (system(" [ ! -d " FILENAME " ]")) {print FILENAME, "is a dir, skipping"; nextfile}} ENDFILE{print FILENAME, FNR}' * */*
a
a 10
a.wk
a.wk 3
b
b 10
dir
dir is a dir, skipping
dir/c
dir/c 10

还要注意 if (system("[ ! -d "FILENAME "]")) {print FILENAME, "is a dir,skipping"; nextfile} 的工作原理与直觉相反:当 true 时它应该返回 1,但它返回退出代码。

我读到A.5 Extensions in gawk Not in POSIX awk :

然后链接的页面显示:

4.11 Directories on the Command Line

According to the POSIX standard, files named on the awk command line must be text files; it is a fatal error if they are not. Most versions of awk treat a directory on the command line as a fatal error.

By default, gawk produces a warning for a directory on the command line, but otherwise ignores it. This makes it easier to use shell wildcards with your awk program:

$ gawk -f whizprog.awk *        Directories could kill this program

If either of the --posix or --traditional options is given, then gawk reverts to treating a directory on the command line as a fatal error.

See Extension Sample Readdir, for a way to treat directories as usable data from an awk program.

事实上,情况确实如此:与之前使用 --posix 相同的命令失败了:

$ gawk --posix 'BEGINFILE{print FILENAME; if (system(" [ ! -d " FILENAME " ]")) {print FILENAME, "is a dir, skipping"; nextfile}} ENDFILE{print FILENAME, NR}' * */*
gawk: cmd. line:1: fatal: cannot open file `dir' for reading (Is a directory)

我检查了上面链接的16.7.6 Reading Directory部分,他们谈论了readdir:

The readdir extension adds an input parser for directories. The usage is as follows:

@load "readdir"

但我既不知道如何调用它,也不知道如何从命令行使用它。

最佳答案

我只是避免将目录传递给 awk,因为即使 POSIX 也说所有文件名参数必须是文本文件。

您可以使用find来遍历目录:

find PATH -type f -exec awk 'program' {} +

关于awk - 如何在awk中跳过目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34018063/

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