Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Shell:在第一个空行之前获取所有行的简单方法_Shell_Awk - Fatal编程技术网

Shell:在第一个空行之前获取所有行的简单方法

Shell:在第一个空行之前获取所有行的简单方法,shell,awk,Shell,Awk,在遇到第一个空行之前,输出文件行的最佳shell命令是什么?例如: output these lines but do not output anything after the above blank line (or the blank line itself) 啊?还有什么吗?这里有一个使用Perl的解决方案: #! perl use strict; use warnings; while (<DATA>) { last if length == 1;

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

output these
lines

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

啊?还有什么吗?

这里有一个使用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
严格使用;
使用警告;
而(){
如果长度=1,则为最后一个;
印刷品;
}
__资料__
输出这些
线
但不要在上面的空行之后输出任何内容
(或空白行本身)
使用sed:

sed '/^$/Q' <file>
sed'/^$/Q'
编辑:sed是一种方式,一种方式,一种方式更快。有关最快的版本,请参见ephemient的答案

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

awk '{if ($0 == "") exit; else print}' <file>
awk'{if($0==“”)退出;else打印}
请注意,我故意写这篇文章是为了避免使用正则表达式。我不知道awk的内部优化是什么样的,但我怀疑直接字符串比较会更快。

sed-e'/^$/,$d'awk解决方案

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

but not this
or this
EOF
awk '/^$/{exit} {print} ' <filename>
awk'/^$/{exit}{print}
几个Perl一行程序 更多信息
awk

awk -v 'RS=\n\n' '1;{exit}'
更多信息
sed

sed -n -e '/./p;/./!q'
sed -e '/./!{d;q}'
sed -e '/./!Q'   # thanks to Jefromi
直接放在贝壳里怎么样

while read line; do [ -z "$line" ] && break; echo "$line"; done
(如果您的shell有bug并且总是处理转义,则使用
printf“%s\n”
而不是
echo

另一个Perl解决方案:

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

也许写得更清楚一点:
sed-e'/^$/,$d'
。此外,如果您碰巧有巨大的文件(或很多),那么读取整个文件可能是一个问题。否则,漂亮又短!我在我的答案中添加了一个sed解决方案,它不会读取整个文件。我喜欢ephemient的sed-e'/./!答案也是。除了给出代码外,解释一下它是如何工作的对我们初学者也有帮助。这很好。我将其调整为以下内容以处理带空格的空行:sed-e'/^\s*$/,$d'perl-pe'exit if m/^$/'(文件名)Joe,您的perl解决方案很好。我真希望我能想到它。@Joe:
m
是多余的,看我的答案
1
比写
{print}
要短,而且做了同样的事情。干得好!第二个sed可以缩短为
“/。/!Q'
-
Q
立即退出,不自动打印+1我尝试了一些计时:
“/!Q'
2.5s<代码>'/./!{d;q}'
5.5s
'/^$/Q'
7.5s。请注意,BSD
sed
(默认安装在OSX上)似乎不支持
Q
Q
修饰符。请注意,BSD
sed
(默认安装在OSX上)似乎不支持
Q
Q
修饰符。
# awk '!NF{exit}1' file
output these
lines
perl -00 -ne 'print;exit' file
perl -00 -pe 'exit if $. == 2' file