str='macOS windows arch-linux ubuntu_linux'
IFS=$' \t\n' # pick the delimiters; also happens to be the default value
set -o noglob # disable the glob part
# add the words resulting from split+glob ($str unquoted) here
# with glob disabled as we don't want a `*` word for instance to
# be expanded to the list of files in the current working directory
arr+=( $str )
一个简单的例子:
arr=()
IFS=$' \t\n'
set -o noglob
printf '1:\n'
str='macOS windows arch-linux ubuntu_linux'
arr+=( $str )
for j in "${!arr[@]}"
do
printf 'arr[%d]="%s"\n' "$j" "${arr[j]}"
done
printf '2:\n'
str='macOS windows arch-linux ubuntu_linux */*'
arr+=( $str )
for j in "${!arr[@]}"
do
printf 'arr[%d]="%s"\n' "$j" "${arr[j]}"
done
如果您
grep
支持非标准-o
选项,使用bash
4.0 或更新版本,您可以执行以下操作:这对于在语言环境中被归类为空格¹的任何字符分隔的单词都有效。
¹ 而
read
基于$IFS
的拆分取决于语言环境和 bash 版本,仅对 ASCII 空格、制表符或换行符,或仅 ASCII 空格(添加 CR、VT、FF)或仅单字节空格可靠地工作......(并且您需要列出所有要拆分的空格字符);并且tr
在 GNU 系统上至少仅适用于单字节字符。如果您的文件只有一行,您可以使用:
如果它可以有多行,一种方法是首先转换文件,以便每个单词都有自己的行,然后使用 bash 的 readarray(仅在 bash 4.0 或更高版本中可用,如果您使用的是 macos,这对您来说可能是一个问题):
初始化一个空数组:
然后,对于读取的每个字符串,使用 split+glob 运算符将空格分隔的单词附加到数组中:
一个简单的例子:
输出: