使用Sed和Regex替换字符串 [英] Replace Strings Using Sed And Regex

查看:87
本文介绍了使用Sed和Regex替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用sed但使用正则表达式取消注释文件内容(例如:[0-9] {1,5})

I'm trying to uncomment file content using sed but with regex (for example: [0-9]{1,5})

# one two 12
# three four 34
# five six 56

以下内容有效:

sed -e 's/# one two 12/one two 12/g' /file

但是,我想使用正则表达式模式替换所有匹配项而无需输入数字,而是将数字保留在结果中.

However, what I would like is to use regex pattern to replace all matches without entering numbers but keep the numbers in the result.

推荐答案

对于符合示例问题,只需

For complying sample question, simply

sed 's/^# //' file

就足够了,但是如果只需要删除某些包含特定正则表达式的行上的注释,则可以使用条件地址:

will suffice, but if there is a need to remove the comment only on some lines containing a particular regex, then you could use conditionnal address:

sed '/regex/s/^# //' file

因此,每个包含regex的行都将不输入(如果开始行带有#)

So every lines containing regex will be uncomented (if line begin with a #)

...,其中regex可能是[0-9]$,如下:

... where regex could be [0-9]$ as:

sed '/[0-9]$/s/^# //' file

将在包含数字作为最后一个字符的行的开头删除#.

will remove # at begin of lines containing a number as last character.

还有

sed '/12$/s/^# //' file

将在以12结尾的行的开头删除#.或者

will remove # at begin of lines ended by 12. Or

sed '/\b\(two\|three\)\b/s/^# //' file

将在包含单词 twothree的行的开头删除#.

will remove # at begin of lines containing word two or three.

这篇关于使用Sed和Regex替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆