我有一个文本文件,我需要删除第一个空白行,然后删除第二个空行后的所有文本

时间:2020-12-29 19:25:18

I'm using bash and I have a file that is in 3 parts of text. The first part, then a blank line, then the 2nd part then another blank line, then the file 3 part of text. I need to output this to a new file that contains only the first 2 parts without the blank line in between. I've been playing with sed and awk, but can't quite figure it out.

我正在使用bash,我有一个文件的3个部分。第一部分,然后是空白行,然后是第二部分,然后是另一个空行,然后是文件的3部分文本。我需要将其输出到一个新文件,该文件只包含前两个部分,中间没有空白行。我一直在玩sed和awk,但无法弄明白。

1 个解决方案

#1


2  

Most simply with awk:

最简单的用awk:

awk -v RS= 'NR <= 2' filename

With an empty record separator RS, awk splits the file into records at empty lines. With the selection NR <= 2, only the first two are printed (delimited by the default output record separator, which is a newline).

使用空记录分隔符RS,awk将文件拆分为空行记录。选择NR <= 2时,仅打印前两个(由默认输出记录分隔符分隔,这是一个换行符)。

If the file is very large, it might be prudent to amend this to

如果文件非常大,修改它可能是谨慎的

awk -v RS= '1; NR == 2 { exit }' filename

This stops processing the file after the second record and prints all until then.

这将停止在第二个记录之后处理文件并在此之前打印所有文件。

Addendum: Obligatory crazy sed solution (not recommended for use, written for fun):

附录:强制性的疯狂sed解决方案(不推荐使用,为了好玩而写):

sed -n '/^$/ { x; /./q; H; d; }; p' filename

#1


2  

Most simply with awk:

最简单的用awk:

awk -v RS= 'NR <= 2' filename

With an empty record separator RS, awk splits the file into records at empty lines. With the selection NR <= 2, only the first two are printed (delimited by the default output record separator, which is a newline).

使用空记录分隔符RS,awk将文件拆分为空行记录。选择NR <= 2时,仅打印前两个(由默认输出记录分隔符分隔,这是一个换行符)。

If the file is very large, it might be prudent to amend this to

如果文件非常大,修改它可能是谨慎的

awk -v RS= '1; NR == 2 { exit }' filename

This stops processing the file after the second record and prints all until then.

这将停止在第二个记录之后处理文件并在此之前打印所有文件。

Addendum: Obligatory crazy sed solution (not recommended for use, written for fun):

附录:强制性的疯狂sed解决方案(不推荐使用,为了好玩而写):

sed -n '/^$/ { x; /./q; H; d; }; p' filename