How do I convert a word into characters using the shell script ? As an example user to "u s e r"
Asked
Active
Viewed 406 times
-1
-
2Possible duplicate of [Bash: Split string into character array](http://stackoverflow.com/questions/7578930/bash-split-string-into-character-array) – sinclair Apr 30 '17 at 12:11
-
2Where is your attempt? Did you even bother to put your exact title into google? Several of the hits on the first page alone would solve your query. – grail Apr 30 '17 at 12:25
-
If it had been tagged `bash`, that would open up using array indexes and a C-style for loop, e.g. `a=user; for ((i=0;i<${#a};i++)); do ((i == 0)) && b=${a:i:1} || b="$b ${a:i:1}"; done` – David C. Rankin Apr 30 '17 at 15:09
2 Answers
3
$ echo user | sed 's/./& /g'
u s e r

jlliagre
- 29,783
- 6
- 61
- 72
-
Very clean use of `&` to refer to the portion of the pattern matched, and POSIX compliant as tagged. – David C. Rankin Apr 30 '17 at 15:06
2
Something like this work fine in bash 4:
$ readarray -t arr < <(grep -o '.' <<<"user")
$ declare -p arr #Just prints the array
declare -a arr=([0]="u" [1]="s" [2]="e" [3]="r")
$ echo "${arr[2]}"
e

George Vasiliou
- 6,130
- 2
- 20
- 27