bash 关联数组的基本错误值非常大

发布于 2024-10-17 21:11:44 字数 505 浏览 2 评论 0原文

我有一个名为 a.txt 的文件,如下所示

7A1123123asd 14
8aasdasdasd 15

现在我编写了一些 bash 代码来读取该文件并根据其中的值构建关联数组

#!/bin/bash
declare -a counter
while read DEAL count; do
    counter["$DEAL"]=$count
done < oasload.job

for i in "${!array[@]}"
do
    echo "key : $i"
    echo "value : ${array[$i]}"
done

不幸的是,当我运行时,出现以下错误

test.sh: line 6: 7A1123123asd: value too great for base (error token is "7A1123123asd")

任何帮助表示赞赏。

I have a file called a.txt which looks as follow

7A1123123asd 14
8aasdasdasd 15

Now I wrote some bash code to read the file and build an associative array from the values in it

#!/bin/bash
declare -a counter
while read DEAL count; do
    counter["$DEAL"]=$count
done < oasload.job

for i in "${!array[@]}"
do
    echo "key : $i"
    echo "value : ${array[$i]}"
done

Unfortunately when I run I get the following error

test.sh: line 6: 7A1123123asd: value too great for base (error token is "7A1123123asd")

Any help appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

坏尐絯℡ 2024-10-24 21:11:44

看起来 bash 将以数字开头的键视为数字。因此,尝试转换 7A 时它会犹豫,因为 A 不是有效的 10 进制数字。例如,如果您可以在所有键上加上 X 前缀,那么这应该可以修复它。

#!/bin/bash
declare -a counter
while read DEAL count; do
    counter["X$DEAL"]=$count
done < oasload.job

for i in "${!array[@]}"
do
    echo "key : $i"
    echo "value : ${array[$i]}"
done

Looks like bash treats keys starting with digits as numeric. So, trying to convert 7A it balks because A is not a valid base-10 digit. If you can e.g. prefix all your keys with X throughout, this should fix it.

#!/bin/bash
declare -a counter
while read DEAL count; do
    counter["X$DEAL"]=$count
done < oasload.job

for i in "${!array[@]}"
do
    echo "key : $i"
    echo "value : ${array[$i]}"
done
喜爱皱眉﹌ 2024-10-24 21:11:44

一切看起来都不错,除了在 Bash 4 中,关联数组是用 -A 声明的。 4 之前的版本不支持关联数组。任何版本中的索引数组都使用 -a 声明,或者使用 array[7]="element"array=( 等语法在赋值时自动创建abc def ghi 123 456)

#!/bin/bash
declare -A counter
while read DEAL count; do
    counter["$DEAL"]=$count
done < oasload.job

for i in "${!array[@]}"
do
    echo "key : $i"
    echo "value : ${array[$i]}"
done

Everything looks OK except that in Bash 4, associative arrays are declared with -A. Versions prior to 4 do not support associative arrays. Indexed arrays in any version are declared using -a or they are created automatically on assignment using syntax such as array[7]="element" or array=(abc def ghi 123 456).

#!/bin/bash
declare -A counter
while read DEAL count; do
    counter["$DEAL"]=$count
done < oasload.job

for i in "${!array[@]}"
do
    echo "key : $i"
    echo "value : ${array[$i]}"
done
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文