Grep remote multiple hosts output to local server

Hello all,
i'm trying to create a report by greping a pattern on multiple remote hosts and creta a simple report,
actually i did this, is ther any better way to do this.

#!/bin/bash
for host in `cat RemoteHosts`
do
  ssh $host -C 'hostname 2>&1; grep ERROR /var/log/WebServer.log.2019-09-21 | wc -l' >> output
done
# joining each two lines together with single tab between
sed 'N;s/\n/ /' output > JoinedLinesReport.csv
#removing old output file
rm -f output

The report with the above script is the following,

server1   1345
server2 2345

Is there any way to create it like this?

HostName Count
server1	        1345
server2	        2345

EDIT: added a new sed to add the line i need.
Thanks any way.

sed -i '1s/^/HostName Count\n/'  JoinedLinesReport.csv
2 Likes
Moderator comments were removed during original forum migration.

It is simpler to put the header before the loop:

echo "HostName Count" > output

A more efficient variant follows.

{
# stdout is redirected in this code block
echo "HostName Count"
for host in `cat RemoteHosts`
do
  ssh $host -C 'hostname 2>&1; grep -c ERROR /var/log/WebServer.log.2019-09-21'
done |
# joining each two lines together with single tab between
  sed 'N;s/\n/ /'
} > JoinedLinesReport.csv

1 Like