我需要替换一个文件夹中的许多文件中的字符串,只有ssh访问服务器。我该怎么做呢?
当前回答
我使用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';
其他回答
使用ack命令会快得多,像这样:
ack '25 Essex' -l | xargs sed -i 's/The\ fox \jump/abc 321/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' {} \;
我从另一篇文章中找到了这篇文章(不记得是哪篇了),虽然不是最优雅的,但它很简单,作为一个新手Linux用户,它没有给我带来任何麻烦
for i in *old_str* ; do mv -v "$i" "${i/\old_str/new_str}" ; done
如果有空格或其他特殊字符,请使用\
for i in *old_str\ * ; do mv -v "$i" "${i/\old_str\ /new_str}" ; done
对于子目录中的字符串使用**
for i in *\*old_str\ * ; do mv -v "$i" "${i/\old_str\ /new_str}" ; done
grep --include={*.php,*.html} -rnl './' -e "old" | xargs -i@ sed -i 's/old/new/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