繁体   English   中英

sed用下划线替换连字符

[英]Sed replace hyphen with underscore

正则表达式新手,有问题。 我想在文件的某些位置用下划线替换连字符。 为了简化起见,假设我要替换第一个连字符。 这是一个示例“文件”:

dont-touch-these-hyphens
leaf replace-these-hyphens

我想在所有找到的行中替换连字符

grep -P "leaf \w+-" file

我试过了

sed -i 's/leaf \(\w+\)-/leaf \1_/g' file

但什么也没发生(错误的更换总比没有好)。 我尝试了一些调整,但仍然没有任何效果。 再次,我对此并不陌生,因此我认为上述“应该基本可行”。 它有什么问题,如何获得我想要的东西? 谢谢。

您可以通过使用两个不同的正则表达式来简化事情; 一种用于匹配需要处理的行,另一种用于匹配必须修改的行。

您可以尝试如下操作:

$ sed '/^leaf/ s/-/_/' file
dont-touch-these-hyphens
leaf replace_these-hyphens

只需使用awk:

$ awk '$1=="leaf"{ sub(/-/,"_",$2) } 1' file
dont-touch-these-hyphens
leaf replace_these-hyphens

它使您可以更精确地控制要匹配的内容(例如,上面的操作是在字符串上进行而不是在“叶子”上进行正则表达式比较,因此即使该字符串包含诸如.*表达式元字符)也可以正常工作更换(如上述只做替换在后文leaf等将继续即使工作leaf本身包含- S):

$ cat file
dont-touch-these-hyphens
leaf-foo.*bar replace-these-hyphens
leaf-foobar dont-replace-these-hyphens

正确的输出:

$ awk '$1=="leaf-foo.*bar"{ sub(/-/,"_",$2) } 1' file
dont-touch-these-hyphens
leaf-foo.*bar replace_these-hyphens
leaf-foobar dont-replace-these-hyphens

错误的输出:

$ sed '/^leaf-foo.*bar/ s/-/_/' file
dont-touch-these-hyphens
leaf_foo.*bar replace-these-hyphens
leaf_foobar dont-replace-these-hyphens

(请注意,leaf-foo中的“-”在最后两行中均由“ _”替换,包括不以字符串“ leaf-foo。* bar”开头的行)。

该awk脚本可以在任何UNIX机器上使用任何awk都按原样工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM