如何在Linux命令行中替换多个文件中的字符串

本文翻译自:How to replace a string in multiple files in linux command line

I need to replace a string in a lot of files in a folder, with only ssh access to the server. 我需要替换文件夹中许多文件中的字符串,而只能通过ssh访问服务器。 How can I do this? 我怎样才能做到这一点?


#1楼

参考:https://stackoom.com/question/lnhe/如何在Linux命令行中替换多个文件中的字符串


#2楼

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

Occurrences of "foo" will be replaced with "bar". 出现的“ foo”将替换为“ bar”。


#3楼

This worked for me: 这为我工作:

find ./ -type f -exec sed -i 's/string1/string2/' {} \;

Howerver, this did not: sed -i 's/string1/string2/g' * . 但是,这没有: sed -i 's/string1/string2/g' * Maybe "foo" was not meant to be string1 and "bar" not string2. 也许“ foo”不是字符串1,“ bar”不是string2。


#4楼

@kev's answer is good, but only affects files in the immediate directory.The example below uses grep to recursively find files. @kev的答案很好,但只影响即时目录中的文件。下面的示例使用grep递归查找文件。 It works for me everytime. 每次都对我有用。

grep -rli 'old-word' * | xargs -i@ sed -i 's/old-word/new-word/g' @

Command breakdown 命令细目

grep -r : --recursive , recursively read all files under each directory. grep的-r:--recursive递归地读每一目录下的所有文件。
grep -l : --print-with-matches , prints the name of each file that has a match, instead of printing matching lines. grep -l-- print -with-matches ,打印每个具有匹配项的文件的名称,而不是打印匹配的行。
grep -i : --ignore-case . grep -i :-- ignore-case

xargs : transform the STDIN to arguments, follow this answer . xargs :将STDIN转换为参数,请遵循以下答案
xargs -i@ ~command contains @~ : a placeholder for the argument to be used in a specific position in the ~command~ , the @ sign is a placeholder which could replaced by any string. xargs的-i @〜命令中包含@〜:到在〜命令〜特定位置被用于参数的占位符,@符号是这可以通过任何字符串替换的占位符。

sed -i : edit files in place, without backups. sed -i :就地编辑文件, 不进行备份。
sed s/regexp/replacement/ : substitute string matching regexp with replacement . sed s / regexp / replacement / :用替换匹配regexp的字符串。
sed s/regexp/replacement/ g : global , make the substitution for each match instead of only the first match. sed s / regexp / replacement / gglobal ,对每个匹配项进行替换,而不是仅对第一个匹配项进行替换。


#5楼

Similar to Kaspar's answer but with the g flag to replace all the occurrences on a line. 与Kaspar的答案类似,但带有g标志来替换一行中的所有匹配项。

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

For global case insensitive: 对于不区分大小写的全局变量:

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

#6楼

grep --include={*.php,*.html} -rnl './' -e "old" | xargs -i@ sed -i 's/old/new/g' @
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值