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


当前回答

对于这个问题,已经列出了一些标准答案。通常,您可以使用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中的示例。

其他回答

要替换多个文件中的字符串,您可以使用:

grep -rl string1 somedir/ | xargs sed -i 's/string1/string2/g'

E.g.

grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'

源的博客

multiedit命令脚本

multiedit [-n PATTERN] OLDSTRING NEWSTRING

根据Kaspar的回答,我编写了一个bash脚本来接受命令行参数,并有选择地限制与模式匹配的文件名。保存在$PATH中并使其可执行,然后使用上面的命令。

剧本如下:

#!/bin/bash
_help="\n
Replace OLDSTRING with NEWSTRING recursively starting from current directory\n
multiedit [-n PATTERN] OLDSTRING NEWSTRING\n

[-n PATTERN] option limits to filenames matching PATTERN\n
Note: backslash escape special characters\n
Note: enclose STRINGS with spaces in double quotes\n
Example to limit the edit to python files:\n
multiedit -n \*.py \"OLD STRING\" NEWSTRING\n"

# ensure correct number of arguments, otherwise display help...
if [ $# -lt 2 ] || [ $# -gt 4 ]; then echo -e $_help ; exit ; fi
if [ $1 == "-n" ]; then  # if -n option is given:
        # replace OLDSTRING with NEWSTRING recursively in files matching PATTERN
        find ./ -type f -name "$2" -exec sed -i "s/$3/$4/g" {} \;
else
        # replace OLDSTRING with NEWSTRING recursively in all files
        find ./ -type f -exec sed -i "s/$1/$2/" {} \;
fi

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

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';

类似于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' {} \;