0

I have an input file (sample.txt)

Sat 02/28/2015__19:32:37.63 
   262,404 K
   100,964 K
   112,052 K
   124,628 K
Sat 02/28/2015__19:37:38.41 
   262,408 K
   100,964 K
   112,056 K
Sun 02/29/2015__16:32:40.11 
   262,443 K
   100,964 K
   112,052 K
   124,628 K
Sun 02/29/2015__16:32:49.20 
   262,408 K
   100,964 K
   112,022 K

I want to print the line with patterns Sat and Sun and then (sum of all the numbers between the two patterns). I want to output something like below

Sat 02/28/2015__19:32:37.63 
600048 
Sat 02/28/2015__19:37:38.41
475463
Sun 02/29/2015__16:32:40.11
600087
Sun 02/29/2015__16:32:49.20 
475394
0
$ awk -F, 'NR>1 && /^[SMTWF]/{print sum;f=0} /^S/{print;sum=0;f=1;next} {sum+=$1$2} END{if (f)print sum}' file
Sat 02/28/2015__19:32:37.63 
600048
Sat 02/28/2015__19:37:38.41 
475428
Sun 02/29/2015__16:32:40.11 
600087
Sun 02/29/2015__16:32:49.20 
475394

How it works

  • -F,

    Use a comma for the field separator.

  • NR>1 && /^[SMTWF]/{print sum;f=0}

    For any line after the first, if it starts with the first letter of a day of the week, then print the sum.

  • /^S/{print;sum=0;f=1;next}

    If the current line starts with the letter S (for Saturday or Sunday), then print the line, initialize the sum to 0, set the flag f to 1, and skip directly to the next line.

  • sum+=$1$2

    For all other lines, add the number to sum. awk would not understand a comma separating the digits. Since a comma was used as the field separator, then $1$2 is the number without the comma which is a form that awk will understand.

  • END{if (f)print sum}

    Print the last remaining sum if we are currently on a Saturday or Sunday group. To accomplish this, we use the flag f. If the last grouping was Monday through Friday, then f==0 and the sum won't print. If it was Saturday or Sunday, then f==1 and it will print.

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.