如何存储 find 生成的文件,即实际文件和内容作为文件而不是 find 的控制台输出?

问题描述

目前我这样做是为了尝试存储 find 命令在我搜索名为 Myfile文件时找到的实际文件及其内容

find /Users/Documents -name Myfile > outputfile

Myfile内容是:

This is my original file.

然而,当我去执行一个操作时,例如 cat outputfile 它需要 find 命令的实际输出,而不是文件本身并显示

/Users/Documents/Myfile

我在等待cat outputfile

This is my original file.

如何存储文件本身并对其执行操作?我的特定用例是对文件执行静态分析,我需要将其作为参数传递。我最近发现使用 find。我不在乎显示命令的输出。我想根据文件查找文件,然后通过将其存储为变量来执行扫描并处理该原始文件内容。我想将它存储为变量的原因是我可以将它作为参数传递给另一个程序。

解决方法

要将文件路径存储在变量中,请使用:

fil=$(find /Users/Documents -name Myfile)

要实际重定向找到的文件的输出,请使用 find 中的 exec 标志,因此:

find /Users/Documents -name Myfile -exec cat '{}' \; > outputfile

如果要将输出存储在变量中而不是重定向到文件,可以使用:

conts=$(find /Users/Documents -name Myfile -exec cat '{}' \;)
,

您可以使用的其他选项如下:

find /Users/Documents -name Myfile | xargs cat > outputfile


find /Users/Documents -name Myfile -print0 | xargs -0 cat > outputfile

-print0 允许在标准输出上打印完整的文件路径,后跟一个空字符和 -0 xargs 标志有效地处理文件名中的空格。

最好的问候