How to grep and count the occurences in while read script?

Hi,

I have a file while is the output of lspath command and output of file is

#cat lspath.txt
Enabled hdisk0 vscsi0
Enabled hdisk0 vscsi1
Enabled hdisk1 vscsi0
Enabled hdisk2 vscsi0
Enabled hdisk2 vscsi1
Missing hdisk3 vscsi0
Enabled hdisk3 vscsi1

Have created script to check state other than "Enabled" as below,

cat lspath.txt |while read STAT HD PATH
do
if [ $STAT != Enabled ];then
echo "The $HD is $STAT state in $PATH"   
else
fi

Having doubt, in the same script how to find out a disk having 2 paths or single path
using any grep or wc or count?. Kindly help

You didn't mention your OS and SHELL!

Modern version of KSH supports associative arrays that can be used for counting:

#!/bin/ksh

typeset -A P
while read status disk path
do
        (( P[$disk]++ ))
done < lspath.txt

for key in ${!P[*]}
do
        print "$key = ${P[$key]}"
done

Output:

hdisk0 = 2
hdisk1 = 1
hdisk2 = 2
hdisk3 = 2

Hi Yoda,

Thanks for posting your reply. I tried the same with "lspath" command instead of the lspath.txt, facing the following error. Pls find the script i modified and the output. FYI - My OS is AIX and shell is KSH

********Script******

#cat lspathavail.sh
typeset -A P
lspath|while read status disk path
do
        (( P[$disk]++ ))
done

for key in ${!P
[*]}
do
        print "$key = ${P[$key]}"
done
#sh -x  lspathavail.sh
+ typeset -A P
fromnet.sh[2]: typeset: 0403-010 A specified flag is not valid for this command.

Pls advice.

Try with typeset -a P

And please use code tags!

--ahamed

By awk:

awk '/Enabled/{++s[$2]} END {for(f in s) print f,s[f]}' lspath.txt

Hi Michael,

Extraordinary !!. Could you pls help to display the state which is not "Enabled" (i.e., Missing) in the same script for the below file.

#cat lspath.txt 
Enabled hdisk0 vscsi0
Enabled hdisk0 vscsi1 
Enabled hdisk1 vscsi0 
Enabled hdisk2 vscsi0 
Enabled hdisk2 vscsi1 
Missing hdisk3 vscsi0 
Enabled hdisk3 vscsi1
awk '{s[$1" "$2]++} END {for(f in s) print f,s[f]}' lspath
1 Like

Hi Pravin,

Thanks, Just amazed. But i feel very tough to understand the awk scripting.

Could you pls guide how your script is working?

Also please share any useful links to learn awk from scratch with examples.

Regards,
Siva