Sunday, April 29, 2012

Bash Script: Read One Character At A Time

I need to count one character at a time from input.txt. How do I read one character at a time under Linux / UNIX bash shell script?

The read builtin can read one character at a time and syntax is as follows:
 
read -n 1 c
echo $c
 
You can setup the while loop as follows:
#!/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/bash
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"
Run it as follows:
/tmp/readch /etc/passwd
Sample outputs:
Letter counter stats:
a = 169
b = 104
c = 39

No comments:

Post a Comment