删除行范围,但跳过行间的注释

删除行范围,但跳过行间的注释

我有一个包含以下内容的文件:

Windows user
I love windows
Windows 10
# I like it
# I want to keep these two lines
Just started with my job
New to shell scripting as well
New to Mac
Please help!

#EOF

我想删除所有行:

从“ I love windows”开始到“ New to shell scripting as well”,但保留这些行之间的注释。

因此,所需的输出应如下所示:

Windows user
# I like it
# I want to keep these two lines
New to Mac
Please help!

#EOF

我使用sed命令删除了使用行号的行范围

sed '2,7d' file

但是这个命令也会删除我想保留的评论。

答案1

尝试使用:

sed '2,7{/^[[:blank:]]*#/!d}' infile

这通常是删除第 2 至第 7 行,但不会删除以井号开头的行(即注释行)。

[[:blank:]]字符类用于匹配并保留那些虽然是注释行但后面还有零个或多个空格的行。

更具体地使用给定的模式:

sed '/I love windows/,/New to shell scripting as well/ {/^[[:blank:]]*#/!d}' infile

标准投诉sed解决方案是:

sed -e '2,7{' -e '/^[[:space:]]*#/!d' -e '}' infile

要从变量中读取行号,只需用双引号括住变量,例如"$line"(有关的如何在 sed 命令中使用变量?

line=2; sed -e "$line"',7{' -e '/^[[:space:]]*#/!d' -e '}' infile

输出为:

Windows user
# I like it
# I want to keep these two lines
New to Mac
Please help!

#EOF

相关内容