Bash Script: Read One Character At A Time

by Vivek Gite on September 30, 2009 · 3 comments

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

See also:

Featured Articles:

Share this with other sys admins!
Facebook it - Tweet it - Print it -

{ 3 comments… read them below or add one }

1 lefty.crupps October 1, 2009

How about a script which runs Bash for me, but its output is slow, one-letter-at-a-time old school terminal looking? For example, when I run this script I am returned to a bash prompt; I run ”ls’ and the returning text is written as a single character every 1/2 second or so.

Useless but I think it sounds retro and fun :)

Reply

2 DougTheBUg July 23, 2010

I don’t know about doing that with bash, but I think it would be cool for log files.

#!/bin/bash
# data file
INPUT=/var/log/messages

# while loop
while IFS= read -r -n1 char
do
# display one character at a time
echo -n “$char”
sleep .05
done < "$INPUT"

Reply

3 DougTheBUg July 23, 2010

Ohh! You could ALSO, include aplay atinysound.wav after the echo line, so you get that uber-cool sound when text prints.

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 6 + 7 ?
Please leave these two fields as-is:
Solve the simple math so we know that you are a human and not a bot.




Previous post:

Next post: