开发者

Shell: simple way to get all lines before first blank line

What's the best shell command to output the lines of a fi开发者_开发知识库le until you encounter the first blank line? For example:

output these
lines

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

awk? something else?


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

but not this
or this
EOF


More awk:

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

More sed:

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

How about directly in shell?

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

(Or printf '%s\n' instead of echo, if your shell is buggy and always handles escapes.)


With sed:

sed '/^$/Q' <file>

Edit: sed is way, way, way faster. See ephemient's answer for the fastest version.

To do this in awk, you could use:

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

Note that I intentionally wrote this to avoid using regular expressions. I don't know what awk's internal optimizations are like, but I suspect direct string comparison would be faster.


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


Awk solution

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


Here's a solution using 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)


A couple of Perl one-liners

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

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


Another Perl solution:

perl -00 -ne 'print;exit' file
perl -00 -pe 'exit if $. == 2' file
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜