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


当前回答

我只是想添加一个注释,一次做两件事-找到一个包含字符串的文件,然后使用find ' chains '方法进行替换:

find  . -type f -iname \*.php -exec fgrep -l "www." {} \; -exec sed -i "s|www||g" {} \;      

在这种实际情况下,从PHP文件中找到的url中删除年代错误的'www'。 'fgrep -l'只在文件中至少找到一个匹配时触发,它不会产生其他输出。别忘了“\;”分隔符!

其他回答

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
cd /path/to/your/folder
sed -i 's/foo/bar/g' *

出现的“foo”将被替换为“bar”。

在像macOS这样的BSD系统上,你需要提供一个备份扩展名,比如-i '.bak',否则每个manpage都会“冒损坏或部分内容的风险”。

cd /path/to/your/folder
sed -i '.bak' 's/foo/bar/g' *

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

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

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

replace "old_string" "new_string" -- *

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

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

真的很蹩脚,但我不能让任何sed命令在OSX上工作,所以我做了这个愚蠢的事情:

:%s/foo/bar/g
:wn

^-复制这三行到我的剪贴板(是的,包括结束换行),然后:

vi *

按住command-v,直到它显示没有文件了。

愚蠢的…出租汽车司机…有效…

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

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

grep的快速解释:

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

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