2

I have a file called output.log which has this content:

Thread started
Thread finished
Thread started
Thread finished
Thread started
Thread started

I monitor its output using:

tail -f output.log

I'd like to write a command to keep a count of how many threads are running right now. For the case above, the output would be:

2 threads are running

Should I perhaps use grep and somehow keep a tally of the string instances?

3

You can use awk to do the counting. Though if nothing more complicated involved you can use

tail -f output.log | awk '/Thread started/{n++}/Thread finished/{n--} END { printf ("%d Threads are running\n", n)}' output.log

Better yet, use watch as follow:

watch -n.2 -x awk '/Thread started/{n++}/Thread finished/{n--} END { printf ("%d Threads are running\n", n)}' output.log

The -n.2 there will refresh every 0.2s as will appear on the top of the screen.

2

You can try the following bash script:

#!/bin/bash
start_count=$(grep -c "started" /path/to/output.log)
finish_count=$(grep -c "finished" /path/to/output.log)
echo "$((start_count - finish_count)) threads are running"

This considers any previously running threads that are out of the printable scope of tail -f. Here we have counted the occurrences of "started" and "finished" in the file and then simply subtract the values to get the result. If you want you choose any range of lines (e.g. tail -30 /path/to/output.log) to read rather than the whole file and then find the result considering those lines.

1

Try running this script,

a=$(grep started output.log | wc -l)

b=$(grep finished output.log | wc -l)

echo Total Running threads: "$[$a-$b]"

Create a bash script and paste the above lines in it. You will get the running threads.

  • 3
    First of all. grep has -c option to do the counting itself. Also when you substract $b from $a you do it in a math context, meaning the syntax becomes echo $((a - b)) – Valentin Bajrami Mar 11 '15 at 13:40

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.