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


当前回答

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

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

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

其他回答

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

:%s/foo/bar/g
:wn

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

vi *

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

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

为了维护我个人的英文节点,我写了一个实用程序脚本,帮助替换多对旧/新字符串,递归为一个目录下的所有文件。

新/旧字符串的多个对在一个散列映射中进行管理。

dir可以通过命令行或环境变量设置,映射是硬编码在脚本中,但如果需要,您可以修改代码从文件加载。

由于一些新特性,它需要bash 4.2。

en_standardize.sh:

#! /bin/bash
# (need bash 4.2+,)
# 
# Standardize phonetic symbol of English.
# 
# format:
#   en_standardize.sh [<dir>]
# 
# params:
# * dir
#   target dir, optional,
#   if not specified then use environment variable "$node_dir_en",
#   if both not provided, then will not execute,
# * 
# 

paramCount=$#

# figure target dir,
if [ $paramCount -ge 1 ]; then # dir specified
    echo -e "dir specified (in command):\n\t$1\n"
    targetDir=$1
elif [[ -v node_dir_en ]]; then # environable set,
    echo -e "dir specified (in environment vairable):\n\t$node_dir_en\n"
    targetDir=$node_dir_en
else # environable not set,
    echo "dir not specified, won't execute"
    exit
fi

# check whether dir exists,
if [ -d $targetDir ]; then
    cd $targetDir
else
    echo -e "invalid dir location:\n\t$targetDir\n"
    exit
fi

# initial map,
declare -A itemMap
itemMap=( ["ɪ"]="i" ["ː"]=":" ["ɜ"]="ə" ["ɒ"]="ɔ" ["ʊ"]="u" ["ɛ"]="e")

# print item maps,
echo 'maps:'
for key in "${!itemMap[@]}"; do
    echo -e "\t$key\t->\t${itemMap[$key]}"
done
echo -e '\n'

# do replace,
for key in "${!itemMap[@]}"; do
    grep -rli "$key" * | xargs -i@ sed -i "s/$key/${itemMap[$key]}/g" @
done

echo -e "\nDone."
exit
grep --include={*.php,*.html} -rnl './' -e "old" | xargs -i@ sed -i 's/old/new/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' {} \;

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

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

E.g.

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

源的博客