0

我正在尝试运行一个 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.

谢谢!

4

3 回答 3

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' *)
于 2013-11-08T11:38:08.567 回答
1

尝试xargs使用sed

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

请注意使用-Z选项 ofgrepnull终止输出,与xargs -0. 这将克服文件名中的空格问题。

于 2013-11-08T11:56:58.683 回答
0

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

find -name 'File*' -exec sed -i 's,OLD,NEW,g' {} \;
于 2013-11-08T12:25:41.583 回答