[英]Replace Strings Using Sed And Regex
I'm trying to uncomment file content using sed but with regex (for example: [0-9]{1,5})我正在尝试使用 sed 但使用正则表达式取消注释文件内容(例如:[0-9]{1,5})
# one two 12
# three four 34
# five six 56
The following is working:以下是工作:
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 :就足够了,但是如果需要仅在包含特定正则表达式的某些行上删除注释,那么您可以使用 conditionnal address :
sed '/regex/s/^# //' file
So every lines containing regex
will be uncomented (if line begin with a #
)因此,包含regex
每一行都将被取消注释(如果行以#
开头)
... where regex
could be [0-9]
as: ...其中regex
可以是[0-9]
为:
sed '/[0-9]/s/^# //' file
will remove #
at begin of every lines containing a number, or将在包含数字的每一行的开头删除#
,或
sed '/[0-9]/s/^# \?//' file
to make first space not needed : #one two 12
, or even使第一个空间不需要: #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
will remove #
at begin of lines ended by 12
.将在以12
结尾的行的开头删除#
。 Or要么
sed '/\b\(two\|three\)\b/s/^# //' file
will remove #
at begin of lines containing word two
or three
.将在包含单词two
或three
的行的开头删除#
。
sed -e 's/^#\s*\(.*[0-9].*\)$/\1/g' filename
应该这样做。
如果您只想取消注释包含数字的那些行,您可以使用以下命令:
sed -e 's/^#\s*\(.*[0-9]+.*\)/\1/g' file
以下sed
命令将取消注释包含数字的行:
sed 's/^#\s*\(.*[0-9]\+.*$\)/\1/g' file
Is the -i
option for replacement in the respective file not necessary?是否不需要在相应文件中替换-i
选项? I get to remove leading #
by using the following:我可以使用以下命令删除前导#
:
sed -i "s/^# \(.*\)/\1/g" file
In order to uncomment only those commented lines that end on a sequence of at least one digit, I'd use it like this:为了仅取消注释以至少一个数字序列结尾的那些注释行,我会像这样使用它:
sed -i "s/^# \(.*[[:digit:]]\+$\)/\1/g" file
This solution requires commented lines to begin with one space character (right behind the #
), but that should be easy to adjust if not applicable.此解决方案要求注释行以一个空格字符开头(就在#
后面),但如果不适用,应该很容易调整。
I find it.我找到它了。 thanks to all of you感谢大家
echo "# one two 12" | grep "[0-9]" | sed 's/# //g'
or要么
cat file | grep "[0-9]" | sed 's/# //g'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.