G
Generic Usenet Account
I had a need for a script that operates on a text file, sorted by
lines, which gives the instance count for each unique pattern in the
file. Using my limited shell-scripting capabilities, I have come up
with something which works. However, I am keen to know how the real
"pros" will approach this problem. My source code follows.
Thanks,
Song
/////////////////////////////////////////////////////////////////////////
#!/bin/ksh
#
# Counts number of repetitions
#
#set -x
USAGE_STR="$0 <file-name>"
function countRepetitions
{
if [ "$#" -ne "0" ]
then
prev=""
count=0
firstTime=1
while read current
do
if [ "$firstTime" -eq "1" ]
then
firstTime=0
prev=$current
else
count=`expr $count + 1`
fi
if [ "$current" != "$prev" ]
then
echo "$prev" : "$count"
count=0
prev=$current
fi
done < $1
fi
}
if [ "$#" == "0" ]
then
echo $USAGE_STR
exit 1
else
if [ ! -f "$1" ]
then
echo "Error: Cannot open file $1"
echo $USAGE_STR
exit 2
fi
fi
countRepetitions $1
exit 0
lines, which gives the instance count for each unique pattern in the
file. Using my limited shell-scripting capabilities, I have come up
with something which works. However, I am keen to know how the real
"pros" will approach this problem. My source code follows.
Thanks,
Song
/////////////////////////////////////////////////////////////////////////
#!/bin/ksh
#
# Counts number of repetitions
#
#set -x
USAGE_STR="$0 <file-name>"
function countRepetitions
{
if [ "$#" -ne "0" ]
then
prev=""
count=0
firstTime=1
while read current
do
if [ "$firstTime" -eq "1" ]
then
firstTime=0
prev=$current
else
count=`expr $count + 1`
fi
if [ "$current" != "$prev" ]
then
echo "$prev" : "$count"
count=0
prev=$current
fi
done < $1
fi
}
if [ "$#" == "0" ]
then
echo $USAGE_STR
exit 1
else
if [ ! -f "$1" ]
then
echo "Error: Cannot open file $1"
echo $USAGE_STR
exit 2
fi
fi
countRepetitions $1
exit 0