I've been trying to use bash to read a file character by character.
After much trial and error, I have discovered that this works:
exec 4<file.txt
declare -i n
while read -r ch <&4;
n=0
while [ ! $n -eq ${#ch} ]
do echo -n "${ch:$n:1}"
(( n++ ))
done
echo ""
done
I.e., I can read it line by line and then loop through each line char by char.
Before doing this, I had tried:
exec 4<file.txt && while read -r -n1 ch <&4; do; echo -n "$ch"; done
but it would skip all whitespaces in the file.
Could you please explain why? Is there a way to make the second strategy (i.e. reading char by char with bash's read) work?


IFSto nothing to have whitespaces survive the word-splitting. – manatwork Oct 1 '12 at 12:30