Coincidir com uma string e imprimir linhas do mesmo bloco que corresponde a outra string

-1

Eu tenho um arquivo grande com mais de 5000 linhas no seguinte formato

Abaixo, o snippet mostra dois blocos do arquivo.

string name    : abcd

    used :metric
    test :ok

{


 fun: add

 fun: sub

 fun: mul

 fun: div

}   


string name    : degh

    used: non -metric
    test: good

{


 fun: per

 fun: div

 fun: add

 fun: mul


}   

O que eu preciso é procurar o string name (por exemplo: abcd ) e, em seguida, imprimir os valores após fun : do bloco string name

Eu gostaria da seguinte saída:

abcd    add
abcd    sub
abcd    mul
abcd    div
degh    per
degh    div
degh    add
degh    mul

Qual seria a maneira correta de resolver esse problema?

    
por user261334 29.08.2014 / 16:30

3 respostas

1

Uma das maneiras de abordá-lo é com perl:

$ perl -lane '$hold=$F[3] if $_ =~ "^string name.*";print "$hold $F[1]" if $F[0] eq "fun:"' bigfile.txt                                                                
abcd add
abcd sub
abcd mul
abcd div
degh per
degh div
degh add
degh mul
    
por Sergiy Kolodyazhnyy 15.11.2017 / 10:03
0
#!/bin/bash

RE_NAME='^ *string name *:' # regex for the 'name' line
RE_FUNSTART='^ *[{] *$'  # regex for the start of the 'fun' block
RE_FUNEND='^ *[}] *$'  # regex for end of 'fun' block
RE_FUN='^ *fun:'  # regex for 'fun' line

while read line; do
 if [[ $line =~ $RE_NAME ]]; then
     name="${line##*: }"
     echo
 elif [[ $line =~ $RE_FUNSTART ]]; then
     fun='1'
 elif [[ $line =~ $RE_FUNEND ]]; then
     fun=''
 elif [[ ($line =~ $RE_FUN) && (-n $fun) ]];  then   # match 'fun' lines only inside 'fun' block
     echo "$name    ${line##*: }"
 fi

done < your_big_file

O Bash pode ser um pouco lento para arquivos grandes. Se for muito lento para você, você poderia portar o código para, por exemplo, Perl ou Python.

    
por Florian Diesch 29.08.2014 / 17:20
0

Outra abordagem com o awk:

 awk '{ if ($1 == "string") name = $4; else if ($1 == "fun:") print name " " $2; }' your_file

Assumindo que " string name " e " : " estão separados por espaço e " fun " é sempre seguido por " : " sem espaço.

    
por Lety 29.08.2014 / 19:49