The read builtin can read one character at a time and syntax is as follows:
You can setup the while loop as follows:
read -n 1 c
echo $c
#!/bin/bash
# data file
INPUT=/path/to/input.txt
# while loop
while IFS= read -r -n1 char
do
# display one character at a time
echo "$char"
done < "$INPUT"
Example: Letter frequency counter shell script
#!/bin/bashRun it as follows:
INPUT="$1"
# counter
a=0
b=0
cc=0
# Make sure file name supplied
[ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 1; }
# Make sure file exits else die
[ ! -f $INPUT ] && { echo "$0: file $INPUT not found."; exit 2; }
# the while loop, read one char at a time
while IFS= read -r -n1 c
do
# counter letter a, b, c
[ "$c" == "a" ] && (( a++ ))
[ "$c" == "b" ] && (( b++ ))
[ "$c" == "c" ] && (( cc++ ))
done < "$INPUT"
echo "Letter counter stats:"
echo "a = $a"
echo "b = $b"
echo "c = $cc"
/tmp/readch /etc/passwd
Sample outputs:
Letter counter stats:
a = 169
b = 104
c = 39
No comments:
Post a Comment