2

I have a .txt file with a sample snapshot of the content shown below. I have to sum all the field values and output them. That is, sum total CEPSDIST (MEAN), sum total SRMR, etc. I want to use bash scripting for this. Any sample scripts to do this?

N.B.: I have never done scripting but using it will make my experimentation and data analysis quick. I am looking forward to learn it but not from scratch, and rather from a sample example from where I can learn backwards.

Individual results
[0001 of 0002]
TARGET   : cheb_M_10_mic_F01_sa1.wav
REFERENCE: orig_mic_F01_sa1.wav
    TIMEDIFF       :      0 samples (0.000 s)
    CEPSDIST (MEAN):   6.96 dB
    CEPSDIST (MED) :   6.74 dB
    SRMR           :   1.06
    LLR      (MEAN):   1.75
    LLR      (MED) :   2.00
    FWSEGSNR (MEAN):  -4.17 dB
    FWSEGSNR (MED) :  -6.12 dB
    PESQ           :   0.07

[0002 of 0002]
TARGET   : cheb_M_20_mic_F01_sa1.wav
REFERENCE: orig_mic_F01_sa1.wav
    TIMEDIFF       :      0 samples (0.000 s)
    CEPSDIST (MEAN):   6.75 dB
    CEPSDIST (MED) :   6.50 dB
    SRMR           :   1.32
    LLR      (MEAN):   1.70
    LLR      (MED) :   2.00
    FWSEGSNR (MEAN):  -3.84 dB
    FWSEGSNR (MED) :  -5.82 dB
    PESQ           :   0.05
1

You can do it with awk:

Here the file extract.awk

BEGIN 
{
    SRMR = 0;
}
{
    if($1 == "SRMR") {SRMR += $3}  
}
END 
{
    print "SRMR sum is: " SRMR;
}

And use it this way:

awk -f extract.awk < your_data_file

EDIT:

All your fields won't be extracted the same way. To understand how a file is parsed with awk, you can use this basic debug file:

# debug.awk
{
    print "For line '" $0 "'"
    print "$1 is '" $1 "'"   
    print "$2 is '" $2 "'"   
    print "$3 is '" $3 "'"   
    print "$4 is '" $4 "'"   
    print "$5 is '" $5 "'"   
    print "$6 is '" $6 "'"
    print ""
}
  • I'd expand it with a switch/case statement - switch ($1) { case "SRMR": SRMR += $3; break etc... but it only works in gawk, and usually only in newer versions. – Dani_l Dec 29 '15 at 7:49
  • Thanks @purplepsycho. Especially the debug.awk was really helpful to understand the workings. – Neeks Dec 29 '15 at 12:20

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.