博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
linux shell 关联数组 hash
阅读量:4162 次
发布时间:2019-05-26

本文共 1123 字,大约阅读时间需要 3 分钟。

shell 的关联数组

Shell Associative Array
   bashi没有原生的对于类似hash table的支持,不像perl或python.
下标数组元素是通过数组下标(数组下标可以是算术表达式,其结果必须是一个整数)来访问的,但是这种访问方式在表达某些关联性很强的数据时会存在限制。
shell 提供了另外一种数组,其可以使用任意的字符串作为下标(不必是整数)来访问数组元素。这种数组叫做关联数组(associative array)。
关联数组的下标和值称为键值对,它们是一一对应的关系。在关联数组中,键是唯一的,值可以不唯一。
shell 的关联数组和 perl 的关联数组在实现功能上是一样的。在 perl 中,关联数组有时候称为哈希(hash)。
定义关联数组
shell 的关联数组和 shell 的下标数组在定义和使用上完全一样,只是在索引上有区别。
需要注意的是,在使用关联数组之前,需要使用命令 declare -A array 进行显示声明。
示例 1
test.sh 文件的内容如下
name=(jim tom lucy)
declare -A phone
phone=([jim]=135 [tom]=136 [lucy]=158)
for i in `eval echo {0..$((${#name[*]}-1))}`
do
 
 
 
 echo ${name[i]} phone number is ${phone["${name[i]}"]}
done
在命令提示符下输入 ./test.sh,执行结果如下:
jim phone number is 135
tom phone number is 136
lucy phone number is 158
操作关联数组的语法
关联数组的操作语法和数组的操作语法完全一致,如下列出常见的操作。
 语法  描述
 ${!array[*]}  取关联数组所有键
 ${!array[@]}  取关联数组所有键
 ${array[*]}  取关联数组所有值
 ${array[@]}  取关联数组所有值
 ${#array[*]}  关联数组的长度
 ${#array[@]}  关联数组的长度
示例 2
test.sh 文件的内容如下
declare -A phone
phone=([jim]=135 [tom]=136 [lucy]=158)
for key in ${!phone[*]}
do
 
 
 
 echo "$key -> ${phone[$key]}"
done
在命令提示符下输入 ./test.sh,执行结果如下:
tom -> 136
jim -> 135
lucy -> 158

转载地址:http://mjixi.baihongyu.com/

你可能感兴趣的文章
Multiple People Tracking by Lifted Multicut and Person Re-identification
查看>>
Multi-Object Tracking with Quadruplet Convolutional Neural Networks
查看>>
关于多目标跟踪的一点理解
查看>>
Learning by tracking:Siamese CNN for robust target association
查看>>
MUSTer:Multi-Store Tracker:A Cognitive Psychology Inspired Approach to Object Tracking
查看>>
Understanding and Diagnosing Visual Tracking Systems
查看>>
Multiple People Tracking by Lifted Multicut and Person Re-identification
查看>>
Visual Tracking Using Attention-Modulated Disintegration and Integration
查看>>
Action-Decision Networks for Visual Tracking with Deep Reinforcement Learning
查看>>
Multiple Object Tracking with High Performance Detection and Appearance Feature
查看>>
深度学习入门(上)-第一章 必备基础知识点
查看>>
ubuntu unzip解压时提示错误 解决方法
查看>>
sprintf函数的说明
查看>>
BOOST_TYPEOF和BOOST_AUTO 作用
查看>>
随机森林概述
查看>>
2011十大战略技术
查看>>
大学应该学的软件知识
查看>>
腾讯与360战争背后的云计算阴影
查看>>
腾讯看了会沉默,360看了会流泪
查看>>
李开复:移动互联网机会最大 微博会现最大赢家
查看>>