문제
첫 번째 빈 줄을 만날 때까지 파일의 줄을 출력하는 최상의 쉘 명령은 무엇입니까? 예를 들어:
output these
lines
but do not output anything after the above blank line
(or the blank line itself)
아? 다른 것?
해결책
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
, 당신의 껍질이 버그가 있고 항상 탈출을 처리한다면.)
# awk '!NF{exit}1' file
output these
lines
SED와 함께 :
sed '/^$/Q' <file>
편집 : SED는 방법, 방식, 방식이 더 빠릅니다. 가장 빠른 버전은 Ephemient의 답변을 참조하십시오.
awk 에서이 작업을 수행하려면 다음을 사용할 수 있습니다.
awk '{if ($0 == "") 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 one-liners
$ 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