I would like to be able to break up an input into multiple characters. For example, I want to be able to break up "Hello World" into h, e, l, l, o, [space], w, o, r, l, d. I am trying to make a Morse Code translator on my Raspberry Pi, and it would save me a lot of time if I can just have individual character translations rather than have to code translations for whole words. Is this possible? Sorry if I sound like I have no idea what I'm talking about, because I kinda don't.
Asked
Active
Viewed 120 times
2 Answers
2
Why are you using Bash? You can use Python or Ruby, to make it simpler. Bash is not really designed for what you're doing.
If you have to use Bash, and I would be careful trusting Bash is available on embedded systems, here's a way to do it (see How to perform a for loop on each character in a string in BASH? for more):
#!/bin/bash
my_string="hello world"
for (( i=0; i<${#my_string}; i++ )); do
echo "${my_string:$i:1}"
done
exit 0
Some Bash resources for dealing with strings and arrays:
- http://tldp.org/LDP/abs/html/arrays.html
- http://tldp.org/LDP/abs/html/string-manipulation.html#STRINGMANIP
To learn Python and/or Ruby:
-
Downvote. You have to quote ``"${my_string:$i:1}"``. Why? Because it will break for something like that ``my_string='thatlittle*asterisk'`` – Aleks-Daniel Jakimenko-A. Dec 27 '13 at 22:55
-
There is nothing "catchy" in it. Any time you see an unquoted variable there is a way to break the code. – Aleks-Daniel Jakimenko-A. Dec 27 '13 at 23:05
-
Another horrible, but possibly more portable way (to other Bourne-like shells) is to use `cut -b` in a loop... – Gert van den Berg Dec 31 '13 at 08:28
1
x is your string y is the character array produced
i=0
while [ $i -lt ${#x} ]; do y[$i]=${x:$i:1}; i=$((i+1));done