This is not bash. This is sh. ${foo:0:1} doesn't work. Results in bad substitution.
foo="Hello"
How do i print each character individually? I am looking for an approach that requires no external commands.
CodePudding user response:
Expanding on my comment: the traditional Bourne shell doesn't really have the sort of built-in facilities for string manipulation that are available in more modern shells. It was expected that you would rely on external program for these features.
For example, using something as simple as cut
, we could write:
foo="hello"
len=$(echo "$foo" | wc -c)
i=1
while [ "$i" -lt "${len}" ]; do
echo "$foo" | cut -c"$i"
i=$(( i 1 ))
done
Which would output:
h
e
l
l
o
Commands like cut
are "standard" shell scripting commands, despite not being built into the shell itself.
CodePudding user response:
As written in larsks's answer you have to rely on external commands.
Instead of running external programs once to get the string length and repeatedly for every index, I suggest to use a single awk
call.
foo="hello world"
awk -v "s=$foo" 'BEGIN { l=length(s); for(i=1; i<=l; i ) print substr(s,i,1)}' /dev/null
which prints
h
e
l
l
o
w
o
r
l
d
Of course you could add further processing to the awk
script or read and process the output like
awk ... | while IFS= read -r char
...