击。检查数组键和值

时间:2017-09-30 23:31:54

标签: arrays bash shell multidimensional-array associative-array

我在Bash(> = 4.2)中有一个无法改变的特殊场景(数据结构)。它是这样的(不确定这是否称为关联数组或多维数组):

#!/bin/bash
declare -gA arrdata
arrdata["jimmy","vacation invoices"]="69008981"
arrdata["jimmy","budget"]="12345678 00392212"
arrdata["mike","budget"]="63859112 98005342 66675431"
arrdata["mike","extra"]="23332587"

我们可以说我们在这个结构上有三种数据。姓名(jimmy或mike),费用类型(预算,额外或度假发票)和数据(以空格分隔的8位数字)。正如我所说,维护阵列奇怪结构的解决方案非常重要,但不能改变。

我需要两个功能。首先检查一个人(一个名字)是否有一种费用("预算"或其他)。该函数将接收两个参数,即所需的名称和类型。例如:

#!/bin/bash
function check_if_expense_exist() {
    #bash code array loops to return 0 if the type exist for the given name, 1 if not exist
}
#Expected results
#Given "jimmy" as first argument and "vacation invoices" as second should return 0
#Given "mike" as first argument and "vacation invoices" as second should return 1

第二个功能应检查数据是否存在。这将收到三个论点。名称(" jimmy"或"迈克"),费用类型("预算"或其他)和数据(8位数字)。

#!/bin/bash
function check_if_data_exist() {
    #bash code array loops to return 0 if data exist for the given name and type of expense, 1 if not exist
}
#Expected results
#Given "jimmy" as first argument and "vacation invoices" as second, and "11111121" as third should return 1 because doesn't exist
#Given "mike" as first argument and "budget" as second, and "98005342" as third should return 0 because it exists

我可以把我不成功的方法放在这里,但说实话......这很痛苦。循环内循环试图将数据显示为分离的变量......但它没有起作用。如果有人坚持我可以粘贴在这里,但我希望有一些" bash guru"可以指导我更好地处理这种复杂的数据结构(至少对我来说很复杂)。感谢。

1 个答案:

答案 0 :(得分:2)

这些功能可能很短:

$ check_if_expense_exist() { [[ -n "${arrdata["$1","$2"]:+not set}" ]]; }
$ check_if_expense_exist jimmy budget && echo y || echo n
y
$ check_if_expense_exist jimmy budgit && echo y || echo n
n
    
$ check_if_data_exist() { [[ "${arrdata["$1","$2"]}" =~ (^| )"$3"( |$) ]]; }
$ check_if_data_exist jimmy budget 12345678 && echo y || echo n
y
$ check_if_data_exist jimmy budget 1234568 && echo y || echo n
n