0

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.

Pooch4716
  • 37
  • 1
  • 5

2 Answers2

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:

To learn Python and/or Ruby:

Community
  • 1
  • 1
Misha M
  • 10,979
  • 17
  • 53
  • 65
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

Bash: Split string into character array

Community
  • 1
  • 1
Tsukasa
  • 6,342
  • 16
  • 64
  • 96