[英]How can I copy files with names containing spaces and UNICODE, when using a shell script?
[英]How to copy files name/path containing spaces in unix?
我的目標是搜索包含模式的文件並將其復制到文件夾中。 這些文件可能在一個文件夾的許多文件夾中可用(例如 /home/abc/logs/....)。 一些文件名和文件夾帶有空格字符,包括空格。 我正在嘗試將找到的結果分配給一個變量並復制它。 但結果是“參數列表太長”
Linux 服務器
pattern="somesttring" ;
LOG_FILE_PATH="/path/to/logs/"
LOGS_TO_COPY=$(grep -Hrn "$pattern" "$LOG_FILE_PATH" | cut -d: -f1)
cp $LOGS_TO_COPY temp #temp is folder to which i have to copy
我收到以下錯誤:
cp $LOGS_TO_COPY temp/
-bash: /bin/cp: Argument list too long
不要將它存儲在變量中,至少不是普通的字符串變量。 字符串變量無法保持每個參數內的空格與分隔它們的空格之間的差異。
grep -lr "$pattern" "$LOG_FILE_PATH" | while IFS= read -r file; do cp "$file" temp/; done
另請注意,您不需要剪切 grep 結果,因為-l
標志只為您提供了文件名,正是您想要的。 -H
是默認值,因此不需要它,如果您只是要切斷它,則-n
是不必要的。
如果您的文件名稱中包含換行符,這將不起作用。 作為一種解決方案,您可以告訴grep
(和read
)使用 NUL 作為分隔符。
grep -lr --null "$pattern" "$LOG_FILE_PATH" | while IFS= read -d $'\0' -r file; do cp "$file" temp/; done
或者,您可以使用xargs
而不是while
+ read
:
grep -lr --null "$pattern" "$LOG_FILE_PATH" | xargs --null -I {} cp {} temp/
如果必須將其存儲在變量中,請使用與上述相同的模式將其存儲到數組變量中。 這種方式不需要空格作為參數分隔符。
declare -a files
while IFS= read -d $'\0' -r file; do files+=("$file"); done < <(grep -lr --null "$pattern" "$LOG_FILE_PATH")
cp "${files[@]}" temp/
這是另一種方法(盡管如果文件名包含換行符,這將不起作用,因為mapfile
不支持更改分隔符):
mapfile -t files < <(grep -lr "$pattern" "$LOG_FILE_PATH")
cp "${files[@]}" temp/
如果要復制的文件數量很大, while
和xargs
解決方案仍然有效,但那些簡單地將整個數組放入一個cp
命令的解決方案可能不會。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.