Goro's answer will work, but it should be noted that command substitution removes trailing newlines as specified by POSIX standard. Thus it may not be desirable where you want to actually iterate over all charactes, even non-printable ones. Another issue is that C-style for loop is used in bash and ksh93, but not in standard (aka POSIX-comliant ) /bin/sh
. The ${variable:index:offset}
form of parameter expansion is also type of bashism and not specified by POSIX definitions of parameter expansion (though supported by ksh93
and zsh
).
Nonetheless, there's a way to iterate over all characters in file portably and in a far more practical way. That's to use awk
:
# all characters on the same line
$ awk '{for(i=1;i<=length;i++){ printf "%c",substr($0,i,1); system("sleep 1");}; print}' input.txt
# all characters on separate lines
$ awk '{for(i=1;i<=length;i++){ print substr($0, i, 1); system("sleep 1"); }}' input.txt
With this command substr()
and system()
are both specified in POSIX awk and will in fact iterate over all characters.
ksh
andzsh
mentioned. Can we start using something like{ba,k,z}sh
maybe ? :) – Sergiy Kolodyazhnyy Sep 08 '18 at 21:33ksh
and Bourne shell, and bash has--posix
flag and supoorts most of the POSIX features. Idk, there's gotta be a better way to phrase it – Sergiy Kolodyazhnyy Sep 09 '18 at 00:28bash
copied a lot fromksh
(and even `zsh); most features that some people call bashisms have originated in other shells (and, obviously, are supported in those shells too). – don_crissti Sep 09 '18 at 10:09