简体   繁体   中英

Using grep to find a pattern through logs and output to a file

I am trying to create a script that greps through some logs for an specific pattern ie:"HelloWorld". The logs are located on different servers that I can ssh to. I have been able to collect the info and output to a file but in order to be more efficient, I would like to be able to number/index the times the instances are found, while still showing the pattern found.

This is what I have:

#!/bin/bash
ips=(*array containing the ip addresses of the servers*)
for j in ${ips[*]}
do
       result=$(ssh abcuser@"$j" "grep -R -i 'HelloWorld' /user/home/doc/abc.log" 2>&1)
       echo "$j has the following errors:
$result"
done

This is able to accomplish 90% of my task, however the 10% is what I am really intested in. I know I can use |wc -l to count the number of instances but I lose the pattern on the output file.

With this code this is what I get:

*ip_1* has the following errors:
2013-12-19 06:37:16,941 HelloWorld error, invoking the handler
2013-12-19 08:30:18,008 [WARN ] HelloWorld invoking error handler
*ip_2* has the following errors:
2013-12-19 13:37:16,941 [WARN ] HelloWorld invoking error handler
2013-12-19 15:30:18,008 HelloWorld error, invoking the handler

However, the following is what I want:

*ip_1* has the following errors:
1-2013-12-19 06:37:16,941 HelloWorld error, invoking the handler
2-2013-12-19 08:30:18,008 [WARN ] HelloWorld invoking error handler
*ip_2* has the following errors:
1-2013-12-19 13:37:16,941 [WARN ] HelloWorld invoking error handler
2-2013-12-19 15:30:18,008 HelloWorld error, invoking the handler

A numerical index that tells me how many instances per server, is it possible? if so, can anyone help me?

Inside the for loop, I would have something like this:

echo "$j has the following errors:"
ssh abcuser@"$j" "grep -R -i 'HelloWorld' /user/home/doc/abc.log" | cat -n

The format is a little different than what you specified though. If you really need that format, you could add the following after "cat -n".

| sed -r 's/^\s*([0-9]+)\s*/\1-/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM