使用sed批量替换字符串时如何提取匹配的变量值?
问题原因
你写的sed命令没有生效主要有三个核心问题:
- sed默认使用基础正则表达式(BRE)模式,该模式下分组用的
()、匹配一次及以上的量词+都需要加反斜杠转义才会被识别为正则语法,未转义时sed会将其当作普通字符匹配,自然无法命中你的文本内容 - 部分系统自带的原生sed(比如macOS默认sed)不支持
\S这种非空格字符简写,替换为通用的[^ ](匹配所有非空格字符)兼容性更好 - 你原命令的替换结果里写了大写的
I,和你预期输出的小写i不一致,会导致最终结果和要求不符
可行解决方案
方案1:使用扩展正则模式(更易读,推荐)
给sed加-r参数(GNU Linux平台)或-E参数(macOS平台)开启扩展正则,不需要额外转义语法符号:
# Linux平台使用 sed -r "s/When i use the connection and request ([^ ]+) using ([^ ]+)/When i send a systemctl command through ssh and request \1 using \2/g" input.txt > output.txt # macOS平台使用 sed -E "s/When i use the connection and request ([^ ]+) using ([^ ]+)/When i send a systemctl command through ssh and request \1 using \2/g" input.txt > output.txt
方案2:使用默认BRE模式适配
如果不想加扩展正则参数,给对应语法符号加转义即可:
sed "s/When i use the connection and request \([^ ]\+\) using \([^ ]\+\)/When i send a systemctl command through ssh and request \1 using \2/g" input.txt > output.txt
验证方法
你可以先不输出到文件,直接在终端执行sed命令打印替换结果,确认符合预期后再写入文件:
sed -r "s/When i use the connection and request ([^ ]+) using ([^ ]+)/When i send a systemctl command through ssh and request \1 using \2/g" input.txt
内容的提问来源于stack exchange,提问作者vance
相关产品推荐
相关产品推荐

