Como contar linhas ordenadas pelo primeiro campo no bash


9

Aqui está um trecho do INPUT:

...
####################
Bala Bela;XXXXXX12345;XXXXXX12345678;A
SERVER345Z3.DOMAIN.com0
SERVER346Z3.DOMAIN.com0
SERVER347Z3.DOMAIN.com0
SERVER348Z3.DOMAIN.com0
ssh-dss ...pubkeyhere...
####################
Ize Jova;XXXXXX12345;XXXXXX12345;A
SERVER342Z3.DOMAIN.com0
SERVER343Z3.DOMAIN.com0
SERVER345Z3.DOMAIN.com0
ssh-rsa ...pubkeyhere...
...

E aqui está um trecho da saída que eu preciso:

Bala Bela;XXXXXX12345;XXXXXX12345678;A
4
Ize Jova;XXXXXX12345;XXXXXX12345;A
3

Então, eu preciso de uma saída do INPUT, para que eu possa ver quantas linhas começando com "SERVER" vão para um determinado usuário (por exemplo: "Bala Bela; XXXXXX12345; XXXXXX12345678; A"). Como posso fazer isso no bash?


Você precisa que isso seja Bash independente ou outras ferramentas são aceitáveis ​​(grep, awk, perl ...)?
Ire_and_curses

Eu assumiria (e o fiz :): que, a menos que seja explicitamente indicado o contrário, uma pergunta de script do bash permite todas as ferramentas padrão como grep, awk, sed, perl e todo o resto.
cas

Respostas:


6
{
i=0
while IFS= read -r line; do
  case "$line" in
    ssh*|'##'*)
      ;;
    SERVER*)
      ((++i))
      ;;
    *)
      if ((i>0)); then echo $i;i=0; fi
      echo "$line"
      ;;
  esac
done
if ((i>0)); then echo $i;i=0; fi
} <inputfile >outputfile

O mesmo no perl one-liner

perl -nle '
  BEGIN{$i=0}
  next if/^(ssh|##)/;
  if(/^SERVER/){++$i;next}
  print$i if$i>0;
  $i=0;
  print;
  END{print$i if$i>0}' inputfile >outputfile

e jogou golfe

perl -nle's/^(ssh|##|(SERVER))/$2&&$i++/e&&next;$i&&print$i;$i=!print}{$i&&print$i' inputfile >outputfile

Uau. perl é surpreendente: D
Gasko Peter

5

Esta versão conta todas as linhas que não correspondem ao regexp na greplinha.

#! /usr/bin/perl 

# set the Input Record Separator (man perlvar for details)
$/ = '####################';

while(<>) {
    # split the rows into an array
    my @rows = split "\n";

    # get rid of the elements we're not interested in
    @rows = grep {!/^#######|^ssh-|^$/} @rows;

    # first row of array is the title, and "scalar @rows"
    # is the number of entries, so subtract 1.
    if (scalar(@rows) gt 1) {
      print "$rows[0]\n", scalar @rows -1, "\n"
    }
}

Resultado:

Bala Bela; XXXXXX12345; XXXXXX12345678; A
4
Ize Jova; XXXXXX12345; XXXXXX12345; A
3

Se você deseja apenas contar linhas que começam com 'SERVIDOR', então:

#! /usr/bin/perl 

# set the Input Record Separator (man perlvar for details)
$/ = '####################';

while(<>) {
    # split the rows into an array
    my @rows = split "\n";

    # $rows[0] will be same as $/ or '', so get title from $rows[1]
    my $title = $rows[1];

    my $count = grep { /^SERVER/} @rows;

    if ($count gt 0) {
      print "$title\n$count\n"
    }
}

5
sed -n ':a /^SERVER/{g;p;ba}; h' file | uniq -c | 
  sed -r 's/^ +([0-9]) (.*)/\2\n\1/'

Resultado:

Bala Bela;XXXXXX12345;XXXXXX12345678;A
4
Ize Jova;XXXXXX12345;XXXXXX12345;A
3

Se uma contagem prefixada estiver correta:

sed -n ':a /^SERVER/{g;p;ba}; h' file |uniq -c

Resultado:

  4 Bala Bela;XXXXXX12345;XXXXXX12345678;A
  3 Ize Jova;XXXXXX12345;XXXXXX12345;A

4

Uma awkalternativa:

/^#{15,}/ {           # if line starts with 15 or more number signs
  if(k) {             # if any key found
    print k RS n      # print it and occurrences of SERVER
    n=0
  }
  getline             # key is on the next line
  k = $0
  next                # move to next record
} 

/SERVER/ { n++ }      # count occurrences of SERVER
END { print k RS n }  # print last record

Tudo em uma linha:

awk '/^#{15,}/ { if(n>0) { print k RS n; n=0 }; getline; k = $0; next } /SERVER/ { n++ } END { print k RS n }'

2

Portanto, se a saída já estiver classificada em cada "bloco", você poderá aplicar o uniq diretamente, verificando apenas os primeiros N caracteres:

cat x | uniq -c -w6

Aqui está N == 6, pois o SERVIDOR consiste em 6 caracteres desde o início da linha. Você terminará com esta saída (que é um pouco diferente da saída necessária):

  1 ####################
  1 Bala Bela;XXXXXX12345;XXXXXX12345678;A
  4 SERVER345Z3.DOMAIN.com0
  1 ssh-dss ...pubkeyhere...
  1 ####################
  1 Ize Jova;XXXXXX12345;XXXXXX12345;A
  3 SERVER342Z3.DOMAIN.com0
  1 ssh-rsa ...pubkeyhere...
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.