Operating System - HP-UX
1847994 Members
7708 Online
104022 Solutions
New Discussion

Simple script for analysis one line.

 
SOLVED
Go to solution
j773303
Super Advisor

Simple script for analysis one line.

Is there simple script to analysis the character of one line?
For ex: "This is Jeff".........how many "f" in this line..... Result is 2

Thanks.
Hero
3 REPLIES 3
Bill Hassell
Honored Contributor
Solution

Re: Simple script for analysis one line.

Nothing simple but this is a start:

STRING="This is Jeff"
LEN=${#STRING}
CNTR=1
QTY=0
if [ $LEN -gt 0 ]
then
while [ $CNTR -le $LEN ]
do
CHAR=$(echo $STRING | cut -c $CNTR)
[[ $CHAR = "f" ]] && let QTY=$QTY+1
let CNTR=$CNTR+1
done
fi
echo "There are $QTY 'f' characters"


Bill Hassell, sysadmin
curt larson_1
Honored Contributor

Re: Simple script for analysis one line.

here is something easy

text="this is jeff"
char="f"

print -- "$text" |
awk -v char="$char" '{
printf("there are %d %s in %s\n",gsub(char,""),char,$0);}'
curt larson_1
Honored Contributor

Re: Simple script for analysis one line.

another way would be

text="this is jeff"
char="f"

chars=$(print -- "$text" | tr -dc "$char" )
numChars=${#chars}
print $numChars