bashmacoskey-value

Get Value from Key:Value Pair with variable as input and output


I have an array of Department Names and Department Codes in a script. A user will select a Department Name which is then assigned to a variable; I need to

# This is an array of Department Namse and matching Department Codes embedded 
# in the script. I have full control over this array.

deptCodeArray="
Information Technology=IT,
Marketing=MA,
Finance=FI
"

# The Department Name will be selected by the user when the script runs 
# (The full script includes a user dialog with a menu of department 3 names 
# to select from.)

departmentName="Information Technology"

# The Department Code is the desired output, to be used later in the script.
# In this case it should be deptCode=IT

deptCode=""


I've tried a couple of different ways to get this working. Apparently macOS does not support associative arrays? I started with "declare -A deptCodeArray" but apparently this requires bash 4, which does not come with macOS, and installing is not an option.

I was trying awk, but I have some trouble understanding how to make that work, and I am not sure if something else would work. I am also not sure if I have the correct syntax for the array.


Solution

  • Here is a way how to do it with bash's =~ operator, which considers the string to the right of it as a regular expression. This example doesn't use arrays, except the BASH_REMATCH (a builtin array whose members are assigned by the =~ operator), and should work in macOS' bash:

    #!/bin/bash
    
    # The variable name is misleading. This isn't a bash array
    deptCodeArray="
    Information Technology=IT,
    Marketing=MA,
    Finance=FI
    "
    
    departmentName="Information Technology"
    
    [[ $deptCodeArray =~ $'\n'"$departmentName"=([^$'\n',]*) ]]
    deptCode=${BASH_REMATCH[1]}
    
    echo "$deptCode"
    

    For more information about =~ operator, see Conditional Constructs, the section starting with [[…]]. For the $'…' construct, see ANSI-C Quoting