while循环列表中的空格

时间:2013-11-08 11:32:49

标签: bash shell while-loop grep

我试图运行for循环,它会替换作为列表传递的文件中的字符串。

示例:

Filename1

Filename2

File name3

File name4

我目前的代码是:

for i in `grep -Rl 'OLD' *`; do                                                                                                                 
> perl -pe 's/OLD/NEW/g' -pi "$i"
> done

Can't open File: No such file or directory.
Can't open name3: No such file or directory.
Can't open File: No such file or directory.
Can't open name3: No such file or directory.
Can't open File: No such file or directory.
Can't open name4: No such file or directory.

谢谢!

3 个答案:

答案 0 :(得分:1)

为了避免分词,你可以说:

grep -Rl 'OLD' * | while read i; do
  perl -pe 's/OLD/NEW/g' -pi "$i";
done

while read i; do
  perl -pe 's/OLD/NEW/g' -pi "$i";
done < <(grep -Rl 'OLD' *)

答案 1 :(得分:1)

尝试将xargssed

一起使用
grep -Rl 'OLD' * -Z | xargs -0 sed -i 's/OLD/NEW/g'

请注意使用-Z grep选项来终止 null 的输出,与xargs -0兼容。这将克服文件名中的空白问题。

答案 2 :(得分:0)

你也可以使用find来做到这一点:

find -name 'File*' -exec sed -i 's,OLD,NEW,g' {} \;