質問
最初の空白行が見つかるまでファイルの行を出力するのに最適なシェルコマンドは何ですか?例:
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
シェルで直接どうですか?
while read line; do [ -z "$line" ] && break; echo "$line"; done
(または、シェルがバギーで常にエスケープを処理する場合、 echo
ではなく printf '%s \ n'
)
# 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
所属していません StackOverflow