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


当前回答

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

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

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

replace "old_string" "new_string" -- *

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

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

其他回答

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

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

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

replace "old_string" "new_string" -- *

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

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

要替换文件中的路径(避免转义字符),您可以使用以下命令:

sed -i 's@old_path@new_path@g'

@符号意味着在接下来的字符串中所有的特殊字符都应该被忽略。

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

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

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

类似于Kaspar的答案,但是用g标记来替换一行上的所有出现。

find ./ -type f -exec sed -i 's/old_string/new_string/g' {} \;

对于全局不区分大小写:

find ./ -type f -exec sed -i 's/old_string/new_string/gI' {} \;

对于这个问题,已经列出了一些标准答案。通常,您可以使用find来递归地列出文件,然后使用sed或perl执行操作。

rpl

对于大多数快速使用,您可能会发现rpl命令更容易记住。

在所有。txt文件上用bar替换foo:

rpl -v foo bar '*.txt' 

模拟替换正则表达式foo。*在所有.txt文件中递归地使用bar:

rpl --dry-run 'foo.*' bar '**/*.txt'

您可能需要安装它(apt-get install rpl或类似的方法)。

repren

然而,对于涉及正则表达式和反向替换,或文件重命名以及搜索和替换的更困难的工作,我所知道的最通用和最强大的工具是repren,这是我不久前为一些棘手的重命名和重构任务编写的一个小Python脚本。你可能更喜欢它的原因是:

支持重命名文件以及搜索和替换文件内容。 在执行搜索和替换之前查看更改。 支持带有反向替换、整词、大小写不敏感和保留大小写(replace foo -> bar, foo -> bar, foo -> bar)模式的正则表达式。 适用于多个替换,包括互换(foo -> bar和bar -> foo)或非唯一替换集(foo -> bar, f -> x)。

使用它,pip安装repren。查看README中的示例。