How find lines, export sum into file?

hello
im working on a bash script to calculate number of viruses found and log on log file.
ive paste some part of log file that are important for this script:

----------- SCAN SUMMARY -----------
Scanned directories: 1063
Scanned files: 8559
Ignored items: 6
Suspicious matches: 137
Viruses found: 1
Fingerprint matches: 0
Data scanned: 199.10 MB
Scan time/item: 0.017 sec
Scan time: 163.698 sec

----------- SCAN SUMMARY -----------
Scanned directories: 4
Scanned files: 1
Ignored items: 0
Suspicious matches: 0
Viruses found: 0
Fingerprint matches: 0
Data scanned: 0.00 MB
Scan time/item: 0.001 sec
Scan time: 0.004 sec

# Skipped - too many resources: 11525 ( > filemax=10000)

----------- SCAN SUMMARY -----------
Scanned directories: 407
Scanned files: 828
Ignored items: 0
Suspicious matches: 1
Viruses found: 14
Fingerprint matches: 0
Data scanned: 36.75 MB
Scan time/item: 0.017 sec
Scan time: 20.494 sec

it has to search the file and find the number in front of the Viruses found phrase, and export sum of these numbers into temp file.
in this case, script pass number 15 into file.log

ive use regix to found but script exit after first result, it cant search all the files content

Viruses found\: (\d+)

Hello

Try:

LOG=/path/to/logfile
TOTAL=0

grep Virus "$LOG" | while read _ _ NUM
	do
		TOTAL=$(( $TOTAL + $NUM ))
	done

echo $TOTAL Viruses found

If that doesnt help, how about show your attempts?

2 Likes

i appreciate your help.
output still 0,
ive trace the code:

[root@srv ~]# bash -x script.sh
+ LOG=/var/log/scan.log
+ TOTAL=0
+ grep Virus /var/log/scan.log
+ read _ _ NUM
+ TOTAL=4
+ read _ _ NUM
+ TOTAL=9
+ read _ _ NUM
+ TOTAL=9
+ read _ _ NUM
+ echo 0
0

That's because with common shells (e.g. bash ) variables defined / created in a subshell (the while loop) are not handed back to the parent shell.

Try also

echo $(( $(grep "Virus" file | grep -o "[^ ]*$" | tr '\n' '+') 0 ))
15

logically echo $TOTAL must print correct number,

It does. In each of the individual and (sort of) independent shell / subshell levels. Look at it as having TWO variables called TOTAL, one in the parent shell, the second in the subshell, initialized from the parent's variable. No way back up.