如何打印我从中 grep 一些行的文件名

How to print the file names from which I grep some lines

我正在尝试使用以下代码从多个 json 文件中获取一些行:

cat $(find ./*/*/folderA/*DTI*.json) | grep -i -E '(phaseencodingdirection|phaseencodingaxis)' > phase_direction

成功了!问题是我不知道哪一行来自哪个文件

有了这个 find ./*/*/preprocessing/*DTI*.json -type f -printf "%f\n" 我可以打印这些名称,但它们出现在末尾并且与它们各自的 phaseencodingdirection|phaseencodingaxis 提取的行顺序不一致。

我不知道如何组合这些代码行来打印从中提取行的文件名及其各自的提取行!?

你能帮帮我吗?

使用文件名作为 grep 的参数而不是 cat

grep -i -H -E '(phaseencodingdirection|phaseencodingaxis)' $(find ./*/*/folderA/*DTI*.json) > phase_direction

即使只有一个文件,-H 选项也会强制 grep 在输出中包含文件名。

但是因为你给 find 的参数是文件名,而不是递归搜索的目录,所以根本没有必要使用它。将通配符直接传递给 grep 即可。也没有必要以 ./ 开头。任何非绝对路径名都相对于当前目录进行解释。

grep -i -H -E '(phaseencodingdirection|phaseencodingaxis)' */*/folderA/*DTI*.json > phase_direction

您可以使用递归 grep:

grep -iER 'phaseencodingdirection|phaseencodingaxis' --include=*DTI*.json */*/folderA

the problem is that I don't know which line comes from which file

嗯,不,你不需要,因为你已经将所有文件的内容连接到一个流中。如果您希望能够在模式匹配点识别每行来自哪个文件,那么您必须首先将该信息提供给 grep。像这样,例如:

find ./*/*/folderA/*DTI*.json |
        xargs grep -i -E -H '(phaseencodingdirection|phaseencodingaxis)' > phase_direction

xargs 程序将从其标准输入读取的行转换为指定命令的参数(在本例中为 grep)。 grep-H 选项使它列出每个匹配项的文件名以及匹配行本身。

或者,同一事物的这种变体更简单一些,并且在某些意义上更接近原始:

grep -i -E -H '(phaseencodingdirection|phaseencodingaxis)' \
    $(find ./*/*/folderA/*DTI*.json) > phase_direction

这将 xargs 排除在外,并将命令替换直接移动到 grep 的参数列表。

但是现在请注意,如果模式 ./*/*/folderA/*DTI*.json 不匹配任何目录,那么 find 实际上并没有为您做任何有用的事情。然后没有目录递归要完成,并且您没有指定任何测试,因此命令替换将简单地扩展到与模式匹配的所有路径,就像扩展 without[ 时模式所做的一样=35=] find。因此,这可能是最好的:

grep -i -E -H '(phaseencodingdirection|phaseencodingaxis)' \
    ./*/*/folderA/*DTI*.json > phase_direction