正则表达式新手,有问题。我想在文件的某些位置用下划线替换连字符。为了简化起见,假设我要替换第一个连字符。这是一个示例“文件”:
dont-touch-these-hyphens
leaf replace-these-hyphens
Run Code Online (Sandbox Code Playgroud)
我想在所有找到的行中替换连字符
grep -P "leaf \w+-" file
Run Code Online (Sandbox Code Playgroud)
我试过了
sed -i 's/leaf \(\w+\)-/leaf \1_/g' file
Run Code Online (Sandbox Code Playgroud)
但什么也没发生(错误的更换总比没有好)。我尝试了一些调整,但仍然没有任何效果。再次,我对此并不陌生,因此我认为上述“应该基本可行”。它有什么问题,如何获得我想要的东西?谢谢。
您可以通过使用两个不同的正则表达式来简化事情;一种用于匹配需要处理的行,另一种用于匹配必须修改的行。
您可以尝试如下操作:
$ sed '/^leaf/ s/-/_/' file
dont-touch-these-hyphens
leaf replace_these-hyphens
Run Code Online (Sandbox Code Playgroud)