insert spaces between characters with pure shell

A file contains: abcdef
I need : a b c d e f

It's easy with sed

sed 's/./& /g'

but this is embedded linux that doesn't have sed/awk. The shell is unknown but it's bashlike. Parameter expansion works and seems promising and. A question mark seems to work as a wildcard, but there doesn't seem to be an equivalent of the ampersand in the sed example.

# foo=abcdef

# echo "${foo//?/& }"
& & & & & & 
# echo "${foo//[a-z]/[a-z] }"
[a-z] [a-z] [a-z] [a-z] [a-z] [a-z]

Any other ideas how to do it in pure shell?

# cat script
#!/bin/bash
if [ $# -ne 1 ] ;then
        echo Usage: $0 [string];exit
fi
for ((s=0;s<${#1};s++))
do
        case $final in
                ^.) final=${1:$s:1};;
                 *) final="$final ${1:$s:1}";;
        esac
done
echo $final

# /temp/script
Usage: /temp/script [string]
# /temp/script abcdef
a b c d e f
1 Like

How about this:

addspace () {
    LEN=${#1}
    for ((c=0;c<$LEN;c++))
    do
       echo -n "${1:$c:1} "
    done
       echo ${1:$LEN:1}
}
addspace "abcdef"

And if your shell dosn't support for loop:

addspace () {
    LEN=${#1}
        c=0
    while [ $c -lt $LEN ]
    do
       echo -n "${1:$c:1} "
           let c=c+1
    done
    echo ${1:$LEN:1}
}
addspace "abcdef"
1 Like

Thanks! Actually, the expansion didn't work correctly when trying offsets but I found a way around with expr substr. All 3 would probably work with a little changing for my particular need, but this was the easiest so it's what I ended up with.

LEN=${#1}
count=1
    while [ "$count" -lt "$LEN" ]
    do
       echo -n "$(expr substr $1 $count 1 ) "
       count=$(($count + 1))
    done
echo

Can I suggest a slight change - to fix last character not output and to support spaces within string:

LEN=${#1}
count=1
while [ "$count" -lt "$LEN" ]
do
    echo -n "$(expr substr "$1" $count 1 ) "
    count=$(($count + 1))
done
echo "$(expr substr "$1" $count 1 )"

Thanks. After I posted and was "finalizing" the script I noticed the missing last letter, which I solved by adding 1 to the length:

LEN=$((${#1} + 1))

I also added the quotes out of habit. I didn't see how they would matter at first since it's taking the first argument. If the argument is abc def, it will see it as abc whether it's quoted or not. But now I see that quoting both the argument on the command line and variable in the script is the only way it will take an argument with spaces using $1.

Luckily I was using

foo "$(can infile)"

and it won't contain any spaces anyway, but that's good to know.