age*_*on7 3 sed text-processing
我有一个包含以下内容的文件:
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
Run Code Online (Sandbox Code Playgroud)
我想删除所有行:
从 " 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
Run Code Online (Sandbox Code Playgroud)
我使用sed
命令使用行号删除行范围
sed '2,7d' file
Run Code Online (Sandbox Code Playgroud)
但是这个命令也会删除我想要保留的评论。
尝试使用:
sed '2,7{/^[[:blank:]]*#/!d}' infile
Run Code Online (Sandbox Code Playgroud)
这通常是删除 2~7 行,而不是删除以散列开头的行,称为注释行。
该[[:blank:]]
字符类用于匹配,并保持这些行,这是一个注释行,但在后面的空格了太零或多个空白。
更具体地说,使用给定的模式:
sed '/I love windows/,/New to shell scripting as well/ {/^[[:blank:]]*#/!d}' infile
Run Code Online (Sandbox Code Playgroud)
标准投诉sed
解决方案是:
sed -e '2,7{' -e '/^[[:space:]]*#/!d' -e '}' infile
Run Code Online (Sandbox Code Playgroud)
要从变量中读取行号,只需双引号您的变量,例如"$line"
(相关:如何在 sed 命令中使用变量?。)
line=2; sed -e "$line"',7{' -e '/^[[:space:]]*#/!d' -e '}' infile
Run Code Online (Sandbox Code Playgroud)
输出是:
Windows user
# I like it
# I want to keep these two lines
New to Mac
Please help!
#EOF
Run Code Online (Sandbox Code Playgroud)