Where I started:
input="a s d f"
content=(`grep -o . <<< "$input"`)
echo ${#content[@]}
for ((a = 0; a < ${#content[@]}; a++)); do
token="${content[a]}"
echo "$token"
done
read -p ''
echoes:
4
a
s
d
f
Although the grep command is capturing white space, when the array is constructed the whitespace characters are being lost. Presumably because spaces are the separation characters when defining an array.
What I want:
content=({a,\ ,s,\ ,d,\ ,f})
echo ${#content[@]}
for ((a = 0; a < ${#content[@]}; a++)); do
token="${content[a]}"
echo "$token"
done
read -p ''
echoes:
7
a
s
d
f
The array length is 7 and the spaces are stored as their own characters. This is what I'm trying to get. However, in this example the input is hard coded in. I'm trying to reach this point from any input string.
What I have:
input="a s d f"
content=({`grep -o . <<< "$input" | sed 's/ /\\\ /g' | sed 's/.*/&,/g'`})
echo ${#content[@]}
for ((a = 0; a < ${#content[@]}; a++)); do
token="${content[a]}"
echo "$token"
done
read -p ''
echoes:
10
{a,
\
,
s,
\
,
d,
\
,
f,}
So I tried to use sed to reformat the way the grep output is returned, that way it would match the pattern in my second example. As you can see this did not work the way I expected.
My Question:
How can I get the result in my second example while still using an input variable to construct the array? Am I just making a stupid mistake? Is this just a bad way to do this in general? Any help would be appreciated.