[英]How to use `file | grep <string>` in a find command?
听起来很简单和天真,我正在努力使用find
和file
命令。 我使用-exec file
是因为我需要获取的特定文件在文件名中没有它们的扩展名,这消除了find
中-name
选项的可能性。 请参阅下面的find
命令和工作区:
workspace=/PATH/
### --- Example hierarchy of where all the files needed are located recursively:
##### -----("$workspace"/ID/ID/DICOM/cat)
####### ------- 'cat' is a .dcm file, without ".dcm" in its name
PETS=`find . -type f -exec file {} \; | grep "DICOM"`
find
: ./PATH/ID/ID/DICOM/cat: DICOM medical imaging data
(一)
默认情况下,我会这样做以将其分配给变量:
PETS=($(find . -type f -exec file {} \; | grep "DICOM"))
但是,我只通过这个 output 获得第一个实例(当有许多其他 DICOM 文件位于与工作目录相关时),这几乎是我当前 output 在 (1) 中的截断版本
./PATH/ID/ID/DICOM/cat:
(2)
我如何从 (1) 或 (2) 或从我的find
命令的修改中实际获取文件本身,以便我可以从 dctmk Toolbox 将其输入到dcmdump
实用程序中?
语法有点复杂,但如果您可以在-exec
操作中同时调用file
和grep
,那么您可以继续链接其他操作而无需任何中间变量。
这样做的方法是创建一个包含file | grep
的显式子 shell。 file | grep
管道: sh -c 'file "$1" | grep -q DICOM'
sh -c 'file "$1" | grep -q DICOM'
。 "$1"
是要检查的文件的占位符,因为 shell 脚本就是这样使用 arguments。 (在脚本中嵌入{}
不是一个好主意。我们会遇到空格和引号等特殊字符的问题。)
那么我们如何设置$1
呢? The answer by appending arguments to the shell command: sh -c '<script>' arg0 arg1 arg2...
sets the positional arguments $0
, $1
, $2
, etc., to the strings arg0
, arg1
, arg2
, and so on. 让我们这样做。 我们可以将$0
设置为sh
,即 shell 的名称; 和$1
到{}
,来自find
的文件名。
这整个-exec
操作可以被视为通过或失败的测试,与-type f
等更简单的测试没有什么不同。 我们可以链接其他条件操作,例如调用dcmdump
。
我们一起得到:
find . -type f -exec sh -c 'file "$1" | grep -q DICOM' sh {} \; -exec dcmdump {} +
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.