![](/img/trans.png)
[英]Bash: Find files containing a certain string and copy them into a folder
[英]Find Files Containing Certain String and Copy To Directory Using Linux
我試圖在當前目錄中查找包含某個字符串的文件,並將所有這些文件復制到一個新目錄中。
我正在嘗試使用的腳本
grep *Qtr_1_results*; cp /data/jobs/file/obj1
我無法復制,輸出消息是:
Usage: cp [-fhipHILPU][-d|-e] [-r|-R] [-E{force|ignore|warn}] [--] src target
or: cp [-fhipHILPU] [-d|-e] [-r|-R] [-E{force|ignore|warn}] [--] src1 ... srcN directory
編輯:清理后(見評論)...
cp *Qtr_1_results* /data/jobs/file/obj1
你正在做的只是一無所獲。 與;
您結束命令並cp
打印錯誤消息,因為您只提供源,而不是目標。
您想要做的是以下內容。 首先,您要搜索文件名,而不是字符串(您沒有提供)。
grep -l the_string_you_are_looking_for *Qtr_1_results*
-l
選項為您提供文件名,而不是找到the_string_you_are_looking_for
的行。 在這種情況下, grep
將搜索文件名包含Qtr_1_results
所有文件。
然后你想將grep
的輸出發送到一個while
循環來處理它。 您可以使用管道 ( |
) 執行此操作。 分號;
只是結束行。
grep -l the_string_you_are_looking_for *Qtr_1_results* | while read -r filename; do cp $filename /path/to/your/destination/folder; done
在while
循環中read -r
會將grep
的輸出放入變量filename
。 當您為變量賦值時,您只需寫出變量的名稱。 當你想擁有變量的值時,你在它前面放一個$
。
您可以在 find 中使用多個 exec 來完成此任務
例如:
find . -type f -exec grep -lr "Qtr_1_results" {} \; -exec cp -r {} /data/jobs/file/obj1 \;
細節:
查找包含該字符串的所有文件。 grep -l 將列出文件。
find . -type f -exec grep -lr "Qtr_1_results" {} \;
第一部分的結果集是文件列表。 將每個文件從結果復制到目標。
-exec cp -r {} /data/jobs/file/obj1 \;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.