-1

I have a large file with more than 5000 lines in the following format

Below snippet shows two blocks of the file.

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


}   

What I need is to search for the string name (eg: abcd) , and then print the values after fun : from that string name's block

I would like the following output:

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

What would be the proper way to solve this problem?

1

One of ways to approach it is with 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
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

Bash may be a bit slow for big files. If it is too slow for you, you could port the code to for example Perl or Python.

  • Hi Florian , First Thanks for quick support. But i have several functions in single block. I want to send the file for your reference, how can i send you the file ?, as i am new here – user261334 Aug 30 '14 at 8:30
  • You can use pastebin and than post url. – Lety Aug 30 '14 at 12:51
  • i added one block of a big file, file is big 1000 lines with several blocks. pastebin.com/dtGuHwb5 – user261334 Sep 1 '14 at 5:31
  • Hi letizia/florin, can u pl advice – user261334 Sep 1 '14 at 6:27
  • we need to find a pattern or a rule, for examples: Device Symmetrix Name : xxx is always what you want to get and add to the subsequent Front Director Paths table? – Lety Sep 2 '14 at 22:36
0

Another approach with awk:

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

Assuming that "string name" and ":" are separated by space and "fun" is always followed by ":" without space.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.