簡體   English   中英

如何使用`文件 | grep<string> ` 在查找命令中?</string>

[英]How to use `file | grep <string>` in a find command?

聽起來很簡單和天真,我正在努力使用findfile命令。 我使用-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"`

我當前的 output,它看起來像一個典型的 output 用於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操作中同時調用filegrep ,那么您可以繼續鏈接其他操作而無需任何中間變量。

這樣做的方法是創建一個包含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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM