我试图从下面的示例文件中填充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 dscpinterface GigabitEthernet1/0/1或GigabitEthernet1/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_sedtest_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 谢谢你的建议。
发布于 2020-02-20 09:22:46
请您试一试:
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]}"
doneIFS.
val)刷新到关联数组中,并为下一次迭代更新接口名称。如果该行不以“接口”开头,则在队列中累积行(数组https://stackoverflow.com/questions/60314554
复制相似问题