我运行这个命令,在我的站点根目录下的所有文件中找到并替换'apple'与'orange'的所有出现:

find ./ -exec sed -i 's/apple/orange/g' {} \;

但它不通过子目录。

这个命令有什么问题?

下面是find ./的输出:

./index.php
./header.php
./fpd
./fpd/font
./fpd/font/desktop.ini
./fpd/font/courier.php
./fpd/font/symbol.php

你的find应该是这样的,以避免将目录名发送到sed:

find ./ -type f -exec sed -i -e 's/apple/orange/g' {} \;

这招对我很管用:

find ./ -type f -exec sed -i '' 's#NEEDLE#REPLACEMENT#' *.php {} \;

我认为我们可以用一行简单的命令做到这一点

for i in `grep -rl eth0 . 2> /dev/null`; do sed -i ‘s/eth0/eth1/’ $i; done

请参阅本页。

对于较大的s&r任务,使用grep和xargs更好更快,因此,例如;

grep -rl 'apples' /dir_to_search_under | xargs sed -i 's/apples/oranges/g'

在linuxOS:

sed -i 's/textSerch/textReplace/g' namefile

如果“sed”不工作,尝试:

perl -i -pe 's/textSerch/textReplace/g' namefile
grep -e apple your_site_root/**/*.* -s -l | xargs sed -i "" "s|apple|orange|"

因为也有macOS的人在阅读这篇文章(就像我一样),下面的代码对我来说是有效的(在10.14上)

egrep -rl '<pattern>' <dir> | xargs -I@ sed -i '' 's/<arg1>/<arg2>/g' @

所有其他使用-i和-e的答案都不能在macOS上运行。

找到了一个很好的程序叫做ruplacer

https://github.com/dmerejkowsky/ruplacer

使用

ruplacer before_text after_text # prints out list of things it will replace
ruplacer before_text after_text --go # executes the replacements

它也尊重.gitignore,所以它不会弄乱你的.git或node_modules目录(找到。默认情况下会进入你的。git目录,可以破坏它!!)