如何找到一个文件,然后将该文件及其内容存储为变量,以便对原始文件运行操作?

问题描述

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

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 找到的文件执行静态分析。我不在乎显示命令的输出。我想根据关键字找到一个文件,然后对该原始文件进行扫描。

解决方法

假设我的目录中有三个文件,分别名为 a.txtb.txtc.txt,内容如下:

$ for file in *.txt; do echo "[$file]"; cat $file; done
[a.txt]
foo
[b.txt]
bar
[c.txt]
foobar

如果我对包含字符串 oo 的所有文件感兴趣,这将起作用:

$ grep -l "oo" *.txt > oo.out
$ cat oo.out
a.txt
c.txt

如果我想要包含 ba 的文件,它是一样的:

$ grep -l "ba" *.txt > ba.out
$ cat ba.out
b.txt
c.txt