![](/img/trans.png)
[英]Problem getting an array of filenames which contain whitespaces in Bash
[英]Invoke sed only on files which contain a certain string - problems with whitespaces in filenames
使用bash,我嘗試在文件中進行替換(用C
替換B
),但僅限於包含特定字符串A
。
我試過了
grep -Rl "A" | xargs sed -i 's/B/C'
但是當文件名包含空格時,這會失敗
作為一個丑陋的解決方法,我提出了以下解決方案,用占位符替換空白:
for FILE in `grep -Rl "A" | tr " " "@"`;
do F1=`echo $FILE | tr "@" " "`;sed 's/B/C/' "$F1";
done
有更優雅的解決方案嗎?
您可以將--null
用於grep
,將-0
用於xargs
:
grep --null -Rl 'A' . | xargs -0 sed -i '' 's/B/C/'
--null
在grep
命令的每個文件名后輸出一個零字節(ASCII NUL字符), xargs -0
讀取到xargs
空終止輸入。
您可以將參數-null for grep的用法與xargs的-0參數結合使用,以使參數由NUL字符分隔。
man grep:
--null Prints a zero-byte after the file name.
man xargs:
-0 Change xargs to expect NUL (``\0'') characters as separators,
instead of spaces and newlines. This is expected to be used in
concert with the -print0 function in find(1).
用於查找文件的UNIX工具被命名,恰當地說, find
grep
。
find . -type f -exec grep -l -Z 'A' {} + |
xargs -0 sed -i 's/B/C'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.