我需要替换一个文件夹中的许多文件中的字符串,只有ssh访问服务器。我该怎么做呢?


当前回答

您也可以使用find和sed,但我发现这一行perl代码工作得很好。

perl -pi -w -e 's/search/replace/g;' *.php

-e表示执行以下代码行。 -i指就地编辑 -w写警告 - p环

(摘自http://www.liamdelahunty.com/tips/linux_search_and_replace_multiple_files.php)

我的最佳结果来自使用perl和grep(以确保文件具有搜索表达式)

perl -pi -w -e 's/search/replace/g;' $( grep -rl 'search' )

其他回答

在MacBook Pro上,我使用了以下方法(灵感来自https://stackoverflow.com/a/19457213/6169225):)

sed -i '' -e 's/<STR_TO_REPLACE>/<REPLACEMENT_STR>/g' *

-i "将确保您没有备份。 -e表示现代正则表达式。

如果字符串中有正斜杠(/),则可以将分隔符更改为'+'。

find . -type f -exec sed -i 's+http://example.com+https://example.com+g' {} +

该命令将在当前目录中递归地运行。

我使用ag, the_silver_searcher:

ag -0 -l 'old' | xargs -0 sed -ri.bak -e 's/old/new/g';

然后git清除。bak文件(rm在git rebase exec中运行时出现bug)

git clean -f '**/*.bak';

假设你想搜索字符串search,并在多个文件中使用replace替换它,这是我久经考验的一行公式:

grep -RiIl 'search' | xargs sed -i 's/search/replace/g'

grep的快速解释:

- r -递归搜索 -i不区分大小写 - i -跳过二进制文件(你想要文本,对吗?) -l输出一个简单的列表。其他命令需要

然后将grep输出通过管道传输到sed(通过xargs),后者用于实际替换文本。-i标志将直接修改文件。把它移开,进行一种“演练”模式。

如果你有可以使用的文件列表

replace "old_string" "new_string" -- file_name1 file_name2 file_name3

如果你有所有可以使用的文件

replace "old_string" "new_string" -- *

如果你有文件扩展名列表,你可以使用

replace "old_string" "new_string" -- *.extension