[英]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.