使用Sed和Regex替换字符串

tan*_*ngi 20 regex string bash replace sed

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

# one two 12
# three four 34
# five six 56
Run Code Online (Sandbox Code Playgroud)

以下是有效的:

sed -e 's/# one two 12/one two 12/g' /file
Run Code Online (Sandbox Code Playgroud)

但是,我想要的是使用正则表达式模式替换所有匹配而不输入数字但保留结果中的数字.

F. *_*uri 16

为了符合样本问题,简单地说

sed 's/^# //' file
Run Code Online (Sandbox Code Playgroud)

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

sed '/regex/s/^# //' file
Run Code Online (Sandbox Code Playgroud)

因此,包含的所有行都regex将被取消(如果行以a 开头#)

...... regex可能是[0-9]$这样的:

sed '/[0-9]$/s/^# //' file
Run Code Online (Sandbox Code Playgroud)

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

  • 我喜欢这个; 意图更清晰了。(您不想“用#号以外的所有内容替换#+一些东西+一个数字+其他东西;您想”删除包含数字的行上的`#`”。)对于`regex` ,您可以说“ [0-9]”以使其只影响其中包含数字的行,或者说“ [0-9] $”,如果数字必须在末尾。 (2认同)

Cha*_*lke 7

sed -e 's/^#\s*\(.*[0-9].*\)$/\1/g' filename
Run Code Online (Sandbox Code Playgroud)

应该这样做.