bash“ read -a”在空分隔的字符串变量上循环 [英] bash “read -a” looping on null delimited string variable
问题描述
我一直在阅读这篇文章: bash 用于循环使用空定界的字符串变量
,看看我是否能够处理数组中包含空格的任意文本。
I've been reading up on this post: bash "for in" looping on null delimited string variable to see if I would be able to handle arbitrary text containing spaces inside an array.
根据文章上面的工作正常:
Based on the post above this works fine:
while IFS= read -r -d '' myvar; do echo $myvar; done < <(find . -type f -print0)
为了检查我的理解,我也这样做了(仍然可以正常工作):
To check my understanding I also did this (which still works fine):
while IFS= read -r -d '' myvar; do echo $myvar; done < <(printf "%s\0" 'a b' 'c d')
但是,然后尝试将输出存储在数组中会出错:
However, then I attempt storing the output in an array it goes wrong:
IFS= read -r -d '' -a myvar < <(printf "%s\0" 'a b' 'c d')
数组仅保存 ab
,而不保存 cd
:
The array holds only a b
and not c d
:
echo ${myvar[@]}
a b
显然,这里有一个更好的细节。谢谢您的帮助。
Apparently, there is a finer detail I am missing here. Thanks for any help.
PS。我正在运行:
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin14)
Copyright (C) 2007 Free Software Foundation, Inc.
推荐答案
在 bash
4.4中, readarray
命令获得了 -d
选项类似于 read
的相同选项。
In bash
4.4, the readarray
command gained a -d
option analogous to the same option for read
.
$ IFS= readarray -d '' myvar < <(printf "%s\0" 'a b' 'c d')
$ printf "%s\n" "${myvar[@]}"
a b
c d
如果必须支持早期版本,则需要显式循环输出。
If you must support earlier versions, you need to loop over the output explicitly.
while IFS= read -d '' line; do
myvar+=( "$line" )
done < <(printf "%s\0" 'a b' 'c d')
这篇关于bash“ read -a”在空分隔的字符串变量上循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!