在日常工作中,有时候分析日志时,常有需要用到二维数组的情况
一、shell中的二维数组用法(shell本事是只支持一维数组的)
利用eval的功能二次解析来实现二维数组
例子来自网上
arr1=(a b c)
arr2=(e f g)
arr3=(h i j)
如何通过二重循环输出上面三个数组上下并置而成的矩阵?代码如下
for ((i=0; i<3; i++)
do
eval tmp=\${arr${i}[@]}
for var in ${tmp}
do
echo -e "${var} \c"
done
echo
done
输出的结果应该就是
a b c
e f g
h i j
在这个例子中内层循环直接用echo "${tmp}"当然更好。
arr2=(e f g)
arr3=(h i j)
如何通过二重循环输出上面三个数组上下并置而成的矩阵?代码如下
for ((i=0; i<3; i++)
do
eval tmp=\${arr${i}[@]}
for var in ${tmp}
do
echo -e "${var} \c"
done
echo
done
输出的结果应该就是
a b c
e f g
h i j
在这个例子中内层循环直接用echo "${tmp}"当然更好。
二、awk中的二维数组使用
awk中的二维数组以至是多维数组array[index1,index2,……],其实是通过把多维下标通过固定分隔符SUBSEP拼接在一起,然后以一维数组的方式进行操作的。SUBSEP是数组下标分割符,默认为“\034”。可以事先设定SUBSEP,也可以直接在SUBSEP的位置输入你要用的分隔符。
1、数组赋值时可以直接使用array[i,j]=value的模式直接赋值
例:a[key1,key2]=value;
2、但是取值的时候就需要注意了,不能直接array[i,j]这种方式去使用。
例:awk 'BEGIN{SUBSEP=":";array["a","b"]=1;for(i in array) print i}'
a:b
例:如果需要取值进行逻辑的话,需要先split一下。
for(item in a){split(item,s,SUBSEP);........
------------------------------------------------------------------
附注:
在SED and AWK中有关于awk多维数组的解释
file_array[2, 4]
This syntax does not create a multidimensional array. It is converted into a string that uniquely identifies the element in a linear array. The components of a multidimensional subscript are interpreted as individual strings ("2" and "4," for instance) and concatenated together separated by the value of the system variable
SUBSEP. The subscript-component separator is defined as
"
\034
"
by default, an unprintable character rarely found in ASCII text. Thus, awk maintains a one-dimensional array and the subscript for our previous example would actually be
"
2\0344
"
(the concatenation of "
2," the value of
SUBSEP, and "
4"). The main consequence of this simulation of multidimensional arrays is that the larger the array, the slower it is to access individual elements.