Skip to content
Advertisement

Using awk command to go through a text file and incrementing counters for morning, afternoon, and night sections of the script

I am using awk to go through a text file that has information of finished scripts then says complete (morning) then informaton of finished scripts then says complete (afternoon) then information of finished scripts then says complete (night).

I am trying to keep track of the finished scripts for each block.

The way I am doing it is…

awk '
    /Completed/ {next} //finished morning block

    /Finished/ {mornCount+=1} //count finishes in morning block

    /Completed/ {next}

    /Finished/ {afterCount+=1}

    /Completed/ {exit}

    /Finished/ {nightCount+=1}

    END{ 
        print "procedures completed this morning: " mornCount 
        print "procedures completed this afternoon: " afterCount
        print "procedures completed at night: " nightCount
    } 
' file.txt

However the values I get for morn, after, and night is the same.

start 
start 
start 
Finished
Finished
Finished
Completed
start 
start 
Finished
Finished 
Completed 
start 
Finished 
Complete 

so I would want 3, 2, and 1 as my output – finishes for (morning, afternoon, and night)

Advertisement

Answer

This should work

awk 'BEGIN{split("morning afternoon night",a)}
     /Finished/{x++}
     /Completed/{print a[++y]":"x;x=0}' file

BEGIN block executes at the start of the script. The split just creates an array like

a[1] = morning 
a[2] = afternoon 
a[3] = night

x is incremented every time Finished is seen
When completed is seen, y is incremented and value from that position in a is printed with the value in x.
x is reset
repeat


Output from your example

morning:3
afternoon:2
night:1
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement