如何忽略重定向文件列表输出的文件名?

Mah*_*dra 4 linux find files

当我使用该命令查找目录及其子目录中的所有文件并将输出重定向到文件 result.txt 中时,然后在 result.txt 文件中,我得到了包括 result.txt 在内的所有文件,但我没有想要结果.txt。

就像我在做的

find . -type f > allfiles.txt
Run Code Online (Sandbox Code Playgroud)

结果我得到了

./test1/test3/file4
./test1/file3
./test2/test4/file6
./test2/file5
./allfiles.txt
Run Code Online (Sandbox Code Playgroud)

如何避免这种情况?

Sté*_*las 16

在这里find,您可以具体执行以下操作:

find . ! -path ./allfiles.txt -type f > allfiles.txt
Run Code Online (Sandbox Code Playgroud)

更一般地,您可以使用 moreutils 的sponge命令将输出文件的创建延迟到命令返回后:

ls -lRA | sponge allfiles.txt
Run Code Online (Sandbox Code Playgroud)

虽然这确实意味着将整个输出存储在内存中。

如果 moreutils 没有安装(它通常不是默认的),你可以实现sponge为:

sponge() {
  perl -0777 -e '$text=<STDIN>;
                 open STDOUT, ">", shift or die$!;
                 print $text' -- "$@"
}
Run Code Online (Sandbox Code Playgroud)


Jar*_*era 8

简单地说,不要将您的 allfiles.txt 文件放入您正在运行 find 的同一目录中。把它放在其他地方,比如:

find . -type f > /tmp/allfiles.txt
Run Code Online (Sandbox Code Playgroud)

或者,如果它必须在同一目录中,请使用 grep 对其进行过滤:

find . -type f | grep -vxF ./allfiles.txt > allfiles.txt
Run Code Online (Sandbox Code Playgroud)

(假设没有其他文件被调用./foo\n./allfiles.txt