如何使用 GNU sed 删除特定行和后面的空白行?

如何使用 GNU sed 删除特定行和后面的空白行?

我有以下文字:

Start-Date: 2013-11-11  07:43:49
Commandline: apt-get install --no-install-recommends catfish

Start-Date: 2013-11-11  11:27:07

Start-Date: 2013-10-16  22:53:02

Start-Date: 2013-10-16  22:55:16

Start-Date: 2013-10-17  22:41:09

Start-Date: 2013-10-17  22:42:02

Start-Date: 2013-10-17  22:42:33

Start-Date: 2013-10-17  22:46:01

Start-Date: 2013-10-17  23:00:06
Commandline: apt-get install shimmer-themes

Start-Date: 2013-10-17  23:01:52
Commandline: apt-get install --no-install-recommends gedit

我想删除以“开始日期”开头的行和以下空白行。换句话说,我只想:

Start-Date: 2013-11-11  07:43:49
Commandline: apt-get install --no-install-recommends catfish

Start-Date: 2013-10-17  23:00:06
Commandline: apt-get install shimmer-themes

Start-Date: 2013-10-17  23:01:52
Commandline: apt-get install --no-install-recommends gedit

我希望我的问题不是重复的删除包含特定字符串的行和以下行

答案1

sed '/^Start-Date:/ {N; /\n$/d}'

sed 是一个流编辑器,可以吸收/识别行组并随心所欲地使用它们。

N是“将换行符和下一个输入行附加到当前缓冲区”,因此\n在缓冲区中是附加行的开始/\n$/d意味着“如果缓冲区中的最后一个附加行为空,则将其全部删除”。

答案2

awk有帮助:

$ awk '{if ($1=="Commandline:") {printf "%s\n%s\n\n", l,$0}; l=$0}' test.txt 
Start-Date: 2013-11-11  07:43:49
Commandline: apt-get install --no-install-recommends catfish

Start-Date: 2013-10-17  23:00:06
Commandline: apt-get install shimmer-themes

Start-Date: 2013-10-17  23:01:52
Commandline: apt-get install --no-install-recommends gedit

答案3

在 Perl 中:

$ perl -ne 'print $last,"$_\n" if /^Commandline/; $last=$_' foo.txt 
Start-Date: 2013-11-11  07:43:49
Commandline: apt-get install --no-install-recommends catfish

Start-Date: 2013-10-17  23:00:06
Commandline: apt-get install shimmer-themes

Start-Date: 2013-10-17  23:01:52
Commandline: apt-get install --no-install-recommends gedit

或者,删除空行:

$ perl -ne 'print $last,$_ if /^Commandline/; $last=$_' foo 
Start-Date: 2013-11-11  07:43:49
Commandline: apt-get install --no-install-recommends catfish
Start-Date: 2013-10-17  23:00:06
Commandline: apt-get install shimmer-themes
Start-Date: 2013-10-17  23:01:52
Commandline: apt-get install --no-install-recommends gedit

-n开关导致perl逐行处理输入文件,并将每一行保存在特殊变量 中$_。如果当前行以 开头,上面的脚本将打印当前行 ( $_) 和上一行 ( ) 。然后它将当前行另存为并移至下一行。$lastCommandline$last

相关内容