bash - 如何将字符串转换为 Bash 中单个字符的数组?

标签 bash

我如何获取一个字符串,比如“Hello World!”并将其拆分为各个字符?

使用上面的例子,我想要一个数组,每个值都有一个字符。所以数组的内部最终看起来像:

{"H", "e", "l", "l", "o", "", "W", "o", "r", "l", "d", “!”

最佳答案

str="Hello world!"
for (( i=0 ; i < ${#str} ; i++ )) {
    arr[$i]=${str:i:1}
}

#print
printf "=%s=\n" "${arr[@]}"

输出

=H=
=e=
=l=
=l=
=o=
= =
=w=
=o=
=r=
=l=
=d=
=!=

您可以使用

将任何命令的结果分配到数组中
mapfile -t array < <(command args)

不幸的是,定义自定义分隔符 -d 需要 bash 4.4.+。比方说,想要将上面的字符串分成 2 个字符 - 使用 grep

mapfile -t -d ''  a2 < <(grep -zo .. <<<"$str")
printf "=%s=\n" "${a2[@]}"

输出:

=He=
=ll=
=o =
=wo=
=rl=
=d!=

关于bash - 如何将字符串转换为 Bash 中单个字符的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43360955/

相关文章:

linux - 对于唯一字段 1,折叠另一个字段中的非唯一条目

linux - '-gt'运算符在Bash编程中是什么意思?

用于交互式 bash 的 C 接口(interface)

bash - 安装 Node 时,我收到有关我的路径的提示

javascript - 从 bash 运行 API javascript

linux - git中的破折号是什么?比如: -a -b -p

regex - Bash:切割每个字符串的分隔片段

linux - 打印文件 bash 列中的所有内容

bash - 如何将 STDERR 重定向到 STDOUT,但忽略原始 STDOUT?

regex - 以自定义格式保存 ldapsearch 的 Bash 脚本