问题描述
我正在尝试使用 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
就足够了,但是如果需要仅在包含特定正则表达式的某些行上删除注释,那么您可以使用conditionnal address:
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
的每一行都将被注释(如果行 begin 带有 #
)
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 every lines containing a number, or
sed '/[0-9]/s/^# ?//' file
使第一个空格不需要:#one two 12
,甚至
sed '/[0-9]$/s/^# //' file
将删除包含数字作为最后一个字符的行开头的 #
.那么
will remove #
at begin of lines containing a number as last character. Then
sed '/12$/s/^# //' file
将在以 12
结尾的行的开头删除 #
.或者
will remove #
at begin of lines ended by 12
. Or
sed '/(two|three)/s/^# //' file
将在包含 word two
或 three
的行的开头删除 #
.
will remove #
at begin of lines containing word two
or three
.
这篇关于使用 Sed 和 Regex 替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!