如何连接由 bash 中的 find 命令找到的文件

ale*_*_si 5 command-line bash

使用 bashfind命令搜索文件,我想将生成的文件连接到一个新文件中。例如,如果 find 命令产生:

find . -name "configuration_dev.txt"

./tmp/configuration1/configuration_dev.txt
./tmp/configuration2/configuration_dev.txt
Run Code Online (Sandbox Code Playgroud)

我想将两个文件的内容直接作为 bash 命令连接到一个新文件中。

pa4*_*080 5

一种可能的方法是通过管道传输findto的输出xargs并通过 连接文件的内容cat,然后您可以将输出重定向到新文件:

find . -name '*file*' | xargs -I{} cat "{}" > output
Run Code Online (Sandbox Code Playgroud)

上面的命令将调用cat每个文件,然后语句的整个输出 xargs将被重定向到该output文件。更有效的方法是使用空分隔符 - 感谢@pLumo的更新:

find . -name '*file*' -print0 | xargs -0 cat > output
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记 xarg 的 `-r` 标志。在找不到文件时运行命令通常不好。 (4认同)
  • 这将为每个文件调用“cat”,您可以只使用“xargs -0 cat”。 (2认同)

ale*_*_si 4

达到预期结果的命令是:

find . -name "configuration_dev.txt" -exec cat > testing.txt {} +
Run Code Online (Sandbox Code Playgroud)

这里提供了对上述行的一个很好的解释:What is Meaning of {} + in find's -exec command?

  • @danzel 这不是问题,只是看起来会是这样,因为 `> cat test.txt` 的位置令人困惑。正如 pLumo 所说,将其放在整个命令的开头或结尾会更清楚。关键是,*`> cat test.txt` 实际上并不是 `find`* 运行的任何命令的一部分。`find` 永远不会看到 `> cat testing.txt`。shell 将该重定向应用于命令“find”。-名称“configuration_dev.txt”-exec cat {} +`。无论“find”运行“cat”多少次(正如您所说,如果文件足够多,这种情况会发生多次)“testing.txt”仅在 shell 打开它时打开一次。 (3认同)