Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: Find Specific records from file and add totals into variables  (Read 4212 times)

0 Members and 1 Guest are viewing this topic.

TDP

    Topic Starter


    Starter

    Hi Eveyone,

    I am working on one shell script to find the specific records from data file and add the totals into variables and print them. you can find the sample data file below for more clarification.

    Sample Data File:

    PXSTYL00__20090803USA
    CHCART00__20090803IND
    SSTRAN00__20090803USA
    Records Sent: 100 Sum1: 10 20090803 1234567890 1234567890 123456789 123456789 123456789
    Records Sent: 200 Sum1: 20 20090803 1234567890 1234567890 123456789 123456789 123456789
    Records Sent: 300 Sum1: 30 20090803 1234567890 1234567890 123456789 123456789 123456789

    In the above sample data file, I want to read all Records with word Records Sent and then get the totals and sums for all records together.

    Out Put Should be like this

    Total Records Sent: 100+200+300 = 600
    Total Sum : 10+20+30 = 60

    I tried the following code:

    total = 0
    sum = 0
    grep "Records Sent:" filename > filename.tmp
    cat filename.tmp |\
    while read line
    do
    tot = `$line | cut -f3 -d " "`
    su = `$line | cut -f5 -d " "`
    total ='expr $total + $total`
    sum =`expr $sum +su`
    done
    echo $total
    echo $sum

    I am having some issues while running this code. Those issues are
    when i am using while read line so it will try to goby line by line but basically it should go by record by record because the Record which has Records Sent: will be 2 lines.
    I had another error saying cannot create. I have no idea why this error is coming.
    Can anybody write above script in different way.Please advise me on this

    Best Regards

    gh0std0g74



      Apprentice

      Thanked: 37
      Re: Find Specific records from file and add totals into variables
      « Reply #1 on: August 09, 2009, 09:31:13 PM »
      try to learn awk

      Code: [Select]
      awk '/Records Sent/{
          total+=$3
          sum+=5
      }
      END{
          print sum, total
      }' file