对bash中带有空格的数组进行切片

问题描述 投票:0回答:1

我想在bash中使用键值存储,然后访问元素并使用它们。到目前为止,我有以下代码,该代码在存储中找到键,但是如果不解释空格就无法从数组中提取值。

对此的直接解决方案(因为我知道每个键将有三个值)是直接访问这些值,但是肯定必须有一种适当地切片数组的方法。

# the array is a key: value storage, the keys do not contain spaces, but the values might
# there are always three values for each key, but the number of words in them is unknown
services=("key1" "some values" "another_value" "a lot of values"
          "key2" "other values" "simple_value2" "a lot of values here"
          "key3" "something else here" "another_value3" "whatever")

# this should look for the given value in the array and return the key and respective values if its found
function find_key () {
    arr=("${@:2}")
    len=$(( ${#arr[@]} -1 ))
    for i in $(seq 0 4 "$len")
    do
    if [[ ${arr[$i]} == "$1" ]] ; then
        # this should get the i'th element and 4 following elements (the values), which works correctly
        result="${arr[*]:$i:4}"
        # at this point result is just a regular array and there is no way to separate the values again

        # this prints just one line with all words
        for x in "${result[@]}"; do
            echo "element: '$x'"
        done

        # I want to return the array ("key" "value 1" "value 2" "the third value") from here to work with it later
        echo "${result[@]}"
        return 0
    fi
    done
    return 1
}

key_and_values="$(find_key "key2" "${services[@]}")"
echo "${key_and_values[@]}"

输出为:

element: 'key2 other values simple_value2 a lot of values here'
key2 other values simple_value2 a lot of values here

我正在寻找:

element: 'key2'
element: 'other values'
element: 'simple_value2'
element: 'a lot of values here'
key2 other values simple_value2 a lot of values here
arrays bash
1个回答
1
投票

更改:

result="${arr[*]:$i:4}"

放入数组:

result=("${arr[@]:$i:4}")

您的脚本存在一些问题:

  • ["${key_and_values[@]}"-key_and_values不是数组,它是普通变量。
  • echo "${result[@]}"将在例如result[0]='-n'时异常工作。使用printf "%s\n" "${result[@]}" | paste -sd ' '或类似名称。
© www.soinside.com 2019 - 2024. All rights reserved.