我想创建包含的数组
Speed: 10500 Mbps
Size: 122400 MB
Load: 4544 Kg
Distance: 232680 miles
Acceleration: 11200 meters/s2
Deviation: 1100 Wierdos
来自以下代码:
read -r -d '' TEST_STRING << EOM
Speed: 10500 Mbps; Size: 122400 MB
Load: 4544 Kg; Distance: 232680 miles
Acceleration: 11200 meters/s2; Deviation: 1100 Wierdos
EOM
STRINGS_ARRAY=()
RE_INTRALINEDELIMITER=";"
while IFS=$'\n' read -a LINE; do
if [[ $LINE =~ $RE_INTRALINEDELIMITER ]]; then
echo "(intraline): $LINE"
while IFS=$';' read -a SUBSTR; do
echo "(substr): $SUBSTR"
done <<< "$LINE"
fi
done <<< "$TEST_STRING"
(添加 echo 用于调试并作为空运算符)。然后用一些函数处理行,最后将其组装回原始字符串。
但是对于 SUBSTR
我只从每个字符串中获得第一个子字符串(分号之前)。我做错了什么?
最佳答案
使用read -ra
,您基本上是读入数组SUBSTR
,但仅尝试在字符串变量的上下文中打印它。尝试打印整个数组,其中应该存储完整的行。
echo "(substr): ${SUBSTR[@]}"
另请注意 LINE
代码中前面的 -a
用法,其中将整行存储为数组。
此外,如果您安装了最新版本的 bash
,请尝试使用 mapfile
/readarray
将多行输出解析为数组。您的整个要求很可能会减少到
re_delimiter=';'
mapfile -t stringArray <<<"$TEST_STRING"
这会将整个字符串存储在数组中,您可以一次循环遍历一个条目以查看该行是否存在 ;
字符。我已在此处初始化了 wholeArray
以存储输入字符串中所有行中的所有 ;
分隔字符串。
wholeArray=()
for line in "${stringArray[@]}"; do
substringArray=()
if [[ $line =~ $re_delimiter ]]; then
IFS=';' read -ra substringArray <<<"$line"
wholeArray+=( "${substringArray[@]}" )
fi
done
现在将整个数组内容打印为
declare -p wholeArray
declare -a wholeArray='([0]="Speed: 10500 Mbps" [1]=" Size: 122400 MB" [2]="Load: 4544 Kg" [3]=" Distance: 232680 miles" [4]="Acceleration: 11200 meters/s2" [5]=" Deviation: 1100 Wierdos")'
(或)使用适当的 for 循环一次打印一个元素
for entry in "${wholeArray[@]}"; do
printf '%s\n' "$entry"
done
还始终使用大写变量来存储变量名称,以免与 shell 维护的环境变量混淆。
关于bash - 将多行分隔子字符串读取到 bash 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47630489/