12

我试过这个命令,

grep '/static' dir/* | xargs sed -i 's/\/static//g'

但我使用的 sed 版本不支持 -i 参数。

要将文件中的字符串替换为与输出相同的输入文件,我通常这样做:

sed 's/\/static//g' filename.txt > new_filename.txt ; mv new_filename.txt filename.txt
4

3 回答 3

27

OS X 的版本sed确实支持-i,但它需要""一个参数来告诉它备份文件(或不备份)使用什么文件扩展名。顺便说一句,您只想grep -l获取文件名。

grep -l '/static' dir/* | xargs sed -i "" 's/\/static//g'
于 2012-08-14T02:24:40.027 回答
3

Use perl:

$ perl -pi.bak -e 's@/static@@g' dir/*
于 2012-08-13T21:14:58.857 回答
1

You can do this using a loop:

for file in $(grep -l '/static' dir/*) ; do
    sed 's/\/static//g' $file > $file.$$ && mv $file.$$ $file
done

I use the .$$ suffix ($$ is the process id of the current shell) to avoid collisions with existing file names, and && rather than ; to avoid clobbering the input file if the sed command fails for some reason. I also added -l so grep prints file names rather than matching lines.

Or you can install GNU sed (I'm not sure exactly how to do that on OSX).

于 2012-08-13T21:33:22.040 回答