Problem
I would like to perform a command on each letter of a string used in a shell script (bin/bash). In the case noted below I will be sending Chinese characters to the "$@" input but there are no spaces and no separators in the string. I am contemplating making use of the string length and then accessing the index of each place in the string: Here's what I have so far (note rdef is a custom command that I've created)
PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin/:
export PATH
for f in "$@"
do
//need to loop through the input and perform action on each index of the $f variable
rdef "$f"|awk -F '\|' '{ gsub(/^ +| +$/, "", $2); print $2 }'
done
Standard input of rdef:
rdef 快乐
Standard output of rdef:
Definition of <快乐>: | kuài lè |
happy
merry
Update
Although the other question is similar it is not the same context. For example in this case I need to split string passed in to a script as an argument. I also need to apply the split string to a chained set of commands. All of which present nuances not covered in the related question.
I've tried the following code which does not seem to work against Chinese characters. When I plug in ASCII characters then the command executes and returns correct results.
PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin/:
export PATH
for f in "$@"
do
foo="$f"
for (( i=0; i<${#foo}; i++ )); do
rdef ${foo:$i:1}|awk -F '\|' '{ gsub(/^ +| +$/, "", $2); print $2 }'
done
done
NB:
My final command line should enable me to execute the custom command chained to awk on each letter:
rdef "$letter-var"|awk -F '\|' '{ gsub(/^ +| +$/, "", $2); print $2 }'
More information on rdef can be found at the following OS question
Solution
All of the solutions offered worked well. I chose the option offered by @kojiro as he pointed me in the proper direction regarding the UTF-8 being required. That was an important discovery as the double byte nature of the Chinese characters was corrupting execution of the loop.
PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin/:
export PATH
LC_CTYPE=UTF-8
x=$1
for ((i=0;i<${#x};i++)); do rdef "${x:i:1}" | awk -F '\|' '{ gsub(/^ +| +$/, "", $2); print $2 }'; done