Bash sed移除#和;从文件到特定关键字的注释

Bash sed移除#和;从文件到特定关键字的注释,bash,sed,Bash,Sed,我有一些文件需要从注释和空白处删除,直到关键字。行号各不相同。是否可以基于关键字限制多个连续的sed替换 这将从文件中删除所有注释和空格: sed -i -e 's/#.*$//' -e 's/;.*$//' -e '/^$/d' file 例如,类似这样的事情: # string1 # string2 some string ; string3 ; string4 #### <Keyword_Keep_this_line_and_comments_white_space_afte

我有一些文件需要从注释和空白处删除,直到关键字。行号各不相同。是否可以基于关键字限制多个连续的sed替换

这将从文件中删除所有注释和空格:

sed -i -e 's/#.*$//' -e 's/;.*$//' -e '/^$/d' file
例如,类似这样的事情:

# string1 
# string2
some string
; string3

; string4
####

<Keyword_Keep_this_line_and_comments_white_space_after_this>
# More comments that need to be here

; etc.
#string1
#string2
一些绳子
; 弦3
; 弦4
####
#更多的评论需要在这里
; 等

我建议使用awk并在到达关键字时设置一个标志:

awk '/Keyword/ { stop = 1 } stop || !/^[[:blank:]]*([;#]|$)/' file
当行包含
关键字时,将
stop
设置为true。当
stop
为true或行与正则表达式不匹配时,执行默认操作(打印行)。正则表达式匹配第一个非空字符为分号或哈希的行或空行。这和你的情况稍有不同,但我认为它符合你的要求

该命令打印到标准输出,因此您应该重定向到新文件,然后覆盖原始文件以实现“就地编辑”:


使用
grep-n关键字
获取包含关键字的行号


当N是包含关键字的行号时,使用
sed-i-e'1,ns/#…
,仅删除第1到N行上的注释。

非常好。一个答案回答了很多问题,谢谢。
awk '...' input > tmp && mv tmp input
sed -i '1,/keyword/{/^[#;]/d;/^$/d;}' file