【问题标题】:Bash. Checking array keys and values重击。检查数组键和值
【发布时间】:2017-09-30 23:31:53
【问题描述】:

我在 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”或“mike”)、费用类型(“预算”或其他)和数据(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 大师”可以指导我更好地处理这种复杂的数据结构(至少对我来说很复杂)。谢谢。

【问题讨论】:

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


    【解决方案1】:

    这些函数可以很短:

    $ 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
    

    【讨论】:

    • 它甚至可以更短,f.e. check_if_expense_exist() [[ ${arrdata["$1,$2"]:+not set} ]]。 :)
    猜你喜欢
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    相关资源
    最近更新 更多