在遇到第一个空行之前,输出文件行的最佳shell命令是什么?例如:

output these
lines

but do not output anything after the above blank line
(or the blank line itself)

AWK?别的什么?

有帮助吗?

解决方案

sed -e '/^$/,$d' <<EOF
this is text
so is this

but not this
or this
EOF

其他提示

更多 awk

awk -v 'RS=\n\n' '1;{exit}'

更多 sed

sed -n -e '/./p;/./!q'
sed -e '/./!{d;q}'
sed -e '/./!Q'   # thanks to Jefromi

直接在shell中怎么样?

while read line; do [ -z "$line" ] && break; echo "$line"; done

(或者 printf'%s \ n'而不是 echo ,如果你的shell有问题,并且总是处理转义。)

# awk '!NF{exit}1' file
output these
lines

使用sed:

sed '/^$/Q' <file>

编辑:sed方式,方式,方式更快。请参阅ephemient的最快版本的答案。

要在awk中执行此操作,您可以使用:

awk '{if (<*> == "") exit; else print}' <file>

请注意,我故意写这篇文章以避免使用正则表达式。我不知道awk的内部优化是什么样的,但我怀疑直接字符串比较会更快。

Awk解决方案

awk '/^$/{exit} {print} ' <filename>

以下是使用Perl的解决方案:

#! perl

use strict;
use warnings;

while (<DATA>) {
    last if length == 1;
    print;
}

__DATA__
output these
lines

but don't output anything after the above blank line
(or the blank line itself)

一些Perl单行

$ perl -pe'last if /^$/' file..

$ perl -lpe'last unless length' file..

另一个Perl解决方案:

perl -00 -ne 'print;exit' file
perl -00 -pe 'exit if $. == 2' file
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top