如何在 Bash 中对字符串中的每个字符执行 for 循环? [英] How to perform a for loop on each character in a string in Bash?
本文介绍了如何在 Bash 中对字符串中的每个字符执行 for 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的变量:
words="这是一条狗。"
我想对每个字符进行 for 循环,一次一个,例如先character="这"
,然后是character="是"
、character="一"
等
I want to make a for loop on each of the characters, one at a time, e.g. first character="这"
, then character="是"
, character="一"
, etc.
我知道的唯一方法是将每个字符输出到文件中的单独行,然后使用while read line
,但这似乎效率很低.
The only way I know is to output each character to separate line in a file, then use while read line
, but this seems very inefficient.
- 如何通过 for 循环处理字符串中的每个字符?
推荐答案
With sed
on dash
shell of LANG=en_US.UTF-8
,我的以下工作正常:
With sed
on dash
shell of LANG=en_US.UTF-8
, I got the followings working right:
$ echo "你好嗎 新年好。全型句號" | sed -e 's/(.)/1
/g'
你
好
嗎
新
年
好
。
全
型
句
號
和
$ echo "Hello world" | sed -e 's/(.)/1
/g'
H
e
l
l
o
w
o
r
l
d
因此,可以使用 while read ... 来循环输出;做 ... ;完成
编辑示例文本翻译成英文:
edited for sample text translate into English:
"你好嗎 新年好。全型句號" is zh_TW.UTF-8 encoding for:
"你好嗎" = How are you[ doing]
" " = a normal space character
"新年好" = Happy new year
"。全型空格" = a double-byte-sized full-stop followed by text description
这篇关于如何在 Bash 中对字符串中的每个字符执行 for 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文