簡體   English   中英

如何在bash中填充多行關聯數組

[英]how to fill multiline associative array in bash

我正在嘗試從以下示例文件中填充 bash 中的關聯數組

interface GigabitEthernet1/0/1
 srr-queue bandwidth share 10 10 60 20
 priority-queue out 
 mls qos trust dscp
interface GigabitEthernet1/0/2
 mls qos trust dscp
interface GigabitEthernet1/0/3
interface GigabitEthernet1/0/4
 srr-queue bandwidth share 10 10 60 20
 priority-queue out 
 mls qos trust dscp
interface GigabitEthernet1/0/5
 srr-queue bandwidth share 10 10 60 20
 priority-queue out 
 mls qos trust dscp
interface GigabitEthernet1/0/6
 srr-queue bandwidth share 10 10 60 20
 priority-queue out 
 mls qos trust dscp
interface GigabitEthernet1/0/7
 srr-queue bandwidth share 10 10 60 20
 priority-queue out 
 mls qos trust dscp
interface GigabitEthernet1/0/8
 srr-queue bandwidth share 10 10 60 20
 priority-queue out 
 mls qos trust dscp

interface GigabitEthernet1/0/1GigabitEthernet1/0/1應該是數組鍵,接口部分之間的任何東西都應該是數組鍵值。

 srr-queue bandwidth share 10 10 60 20
 priority-queue out 
 mls qos trust dscp

預期輸出應該是:

 $echo ${array[GigabitEthernet1/0/4]}
 srr-queue bandwidth share 10 10 60 20
 priority-queue out 
 mls qos trust dscp

會有多個格式相似的不同文件,所以這需要循環完成,界面之間的文本應該是0到5-6行。 背后的原因是我需要對每個接口進行邏輯測試,如果它正確與否。 下面的文本是正確的,其他任何內容或空白字段都是不正確的。

 srr-queue bandwidth share 10 10 60 20
 priority-queue out 
 mls qos trust dscp

到目前為止,我一直堅持將 IFS 和多行的格式設置為數組鍵的值。 我能夠填充非關聯數組,但不是最干凈的形式。

$ cat test_compare_interface | sed 's/interface.*$/*\n&/g' > test_compare_interface_sed

test_compare_interface 是帶有接口的文件

$ IFS=$'*' && array=($(cat test_compare_interface_sed))
$ echo ${array[4]}

interface GigabitEthernet1/0/4
 srr-queue bandwidth share 10 10 60 20
 priority-queue out 
 mls qos trust dscp

使用關聯數組循環,我還在掙扎

while IFS='*' read -r interface value; do array[$interface]=$value ; done < test_compare_interface_sed 

謝謝你的所有建議。

請您嘗試以下操作:

declare -A array

# assign "${val[*]}" to the assciative array "array" keying with $1
store() {
    if [[ -n $1 ]]; then        # will skip the 1st line which is not ready
        array[$1]=$(IFS=$'\n'; echo "${val[*]}")
                                # join "val" with newline
        unset val               # empty the queue
    fi
}

while IFS= read -r line; do
    if [[ $line =~ ^interface ]]; then
        store "$interface"      # assign to the associative array
        interface="$line"       # for the next iteration
    else
        val+=("${line# }")      # append to the queue
    fi
done < file.txt

store "$interface"              # flush the last entry

for i in "${!array[@]}"; do     # print the array elements to test
    echo "$i"
    echo "${array[$i]}"
done
  • 它只是逐行讀取輸入而不修改IFS
  • 如果該行以“interface”開頭,它會將隊列(數組val )刷新到關聯數組中,並為下一次迭代更新接口名稱。
  • 如果該行不以“interface”開頭,則該行在隊列中累積(數組val

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM