2009-12-13 41 views

回答

41

的方法有很多。但其中一个答案是:

find . -name '*.html' |xargs perl -pi -e 's/find/replace/g' 
6

我总是这样做,与编脚本前的脚本

for i in "[email protected]"; do ex - "$i" << 'eof'; done 
%s/old/new/ 
x 
eof 

命令仅仅是:从VI线模式。

+0

这具有明显的优势,您可以执行更复杂的编辑。 – alastair 2013-05-13 14:10:54

2

最近的bash shell,假设你不需要遍历目录

for file in *.txt 
do 
while read -r line 
do 
    echo ${line//find/replace} > temp   
done <"file" 
mv temp "$file" 
done 
21

像僵尸溶液(快我假设),但sed的(许多发行版和OSX标准),而不是的Perl:

find . -name '*.py' | xargs sed -i .bak 's/foo/bar/g' 

这将替换所有富在当前目录下的Python文件 OCCURENCES与酒吧并使用.py.bak扩展名为每个文件创建一个备份。

,并删除德.bak文件:

find . -name "*.bak" -delete 
+0

这会影响搜索之外的空白。它似乎在我的每个文件的末尾添加了新行。 – Shane 2013-05-09 17:38:43

+0

每个版本的sed都不支持AFAIK in-place编辑;我认为这是一个GNU扩展。 – alastair 2013-05-13 14:06:13

+0

这是一个GNU扩展,至少在我的版本中它必须是 'sed -i.bak' (没有空格) – friedemann 2014-08-28 16:00:22

4

使用find和sed用名或目录与空间的使用这样的:

find . -name '*.py' -print0 | xargs -0 sed -i 's/foo/bar/g' 
的[查找和替换在多个特定的词