使用grep+sed批量替换文本失败,求助解决报错问题
批量替换文本失败的修复方案
错误原因解析
sed no input files:你用管道把grep的输出传给sed -i,但sed -i是用来直接修改文件的,需要接收文件名作为参数,而非从管道读取文本内容,所以sed找不到要处理的文件。BRF/Test_page.mujebr3.brf: binary file matches:grep -r默认会扫描二进制文件,这类文件不适合用文本替换工具修改,还会干扰正常处理流程。
正确命令示例
方案一:grep + xargs(Linux系统适用)
grep -r --files-with-matches --binary-files=without-match "david_now" | xargs sed -i 's/david_now/david_old/g'
参数说明:
--files-with-matches:只输出包含目标文本的文件名,不输出匹配的行内容--binary-files=without-match:跳过二进制文件,不将其纳入处理列表xargs:把grep输出的文件名批量传给sed,让sed -i能直接操作文件
方案二:适配BSD/macOS系统
macOS的sed是BSD版本,-i参数需要指定备份后缀(空字符串表示不生成备份文件),命令调整为:
grep -r --files-with-matches --binary-files=without-match "david_now" | xargs sed -i '' 's/david_now/david_old/g'
方案三:find命令替代(跨平台通用)
find . -type f -exec grep -q "david_now" {} \; -exec sed -i 's/david_now/david_old/g' {} \;
参数说明:
-type f:只处理普通文本文件-exec grep -q "david_now" {} \;:静默检查文件是否包含目标文本,不输出冗余内容-exec sed ... {} \;:对符合条件的文件执行替换操作
内容的提问来源于stack exchange,提问作者CPUDave
相关产品推荐
相关产品推荐

