Shell: maneira simples de obter todas as linhas antes da primeira linha em branco

StackOverflow https://stackoverflow.com/questions/1603389

  •  05-07-2019
  •  | 
  •  

Pergunta

O que é o melhor comando a saída das linhas de um arquivo até encontrar a primeira linha em branco? Por exemplo:

output these
lines

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

awk? outra coisa?

Foi útil?

Solução

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

but not this
or this
EOF

Outras dicas

Mais awk:

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

Mais sed:

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

Como sobre diretamente no shell?

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

(ou printf '%s\n' vez de echo, se o seu shell é buggy e sempre lida com escapes.)

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

Com o sed:

sed '/^$/Q' <file>

Edit: sed é o caminho, caminho, caminho mais rápido. Veja a resposta de ephemient para a versão mais rápida.

Para fazer isso no awk, você poderia usar:

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

Note que escrevi intencionalmente este evitar o uso de expressões regulares. Eu não sei o que otimizações internas do awk são como, mas eu suspeito comparação de seqüência direta seria mais rápido.

solução Awk

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

Aqui está uma solução usando 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)

Um par de Perl one-liners

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

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

Outra solução Perl:

perl -00 -ne 'print;exit' file
perl -00 -pe 'exit if $. == 2' file
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top