用awk進行文本處理,少不了就是它的數組處理。那么awk數組有那些特點,一般常見運算又會怎么樣呢。我們先看下以下的一些介紹,結合樣例我們會解說下它的不同之處。在 awk 中數組叫做關聯數組(associative arrays),由于下標記能夠是數也能夠是串。awk 中的數組不必提前聲明,也不必聲明大小。數組元素用 0 或空串來初始化,這依據上下文而定。比如:
?
一、定義方法
?
1:能夠用數值作數組索引(下標)
Tarray[1]=“cheng mo” Tarray[2]=“800927”
2:能夠用字符串作數組索引(下標)
Tarray[“first”]=“cheng ” Tarray[“last”]=”mo” Tarray[“birth”]=”800927”
使用中 print Tarray[1] 將得到”cheng mo” 而 print Tarray[2] 和 print[“birth”] 都將得到 ”800927” 。
?
二、數組相關函數
[chengmo@localhost ~]$ awk --version
GNU Awk 3.1.5使用版本號是:3.1以上,不同版本號以下函數不一定同樣
- 得到數組長度(length方法使用)
[chengmo@localhost ~]$ awk 'BEGIN{info="it is a test";lens=split(info,tA," ");print length(tA),lens;}'
4 4length返回字符串以及數組長度,split進行切割字符串為數組,也會返回切割得到數組長度。
?
(asort使用):
[chengmo@localhost ~]$ awk 'BEGIN{info="it is a test";split(info,tA," ");print asort(tA);}'
4asort對數組進行排序,返回數組長度。
?
- 輸出數組內容(無序,有序輸出):
[chengmo@localhost ~]$ awk 'BEGIN{info="it is a test";split(info,tA," ");for(k in tA){print k,tA[k];}}'
4 test
1 it
2 is
3 a?
for…in 輸出,由于數組是關聯數組,默認是無序的。所以通過for…in 得到是無序的數組。假設須要得到有序數組,須要通過下標獲得。
?
[chengmo@localhost ~]$ awk 'BEGIN{info="it is a test";tlen=split(info,tA," ");for(k=1;k<=tlen;k++){print k,tA[k];}}'?
1 it
2 is
3 a
4 test注意:數組下標是從1開始,與c數組不一樣。
?
?
- 推斷鍵值存在以及刪除鍵值:
一個錯誤的推斷方法:
[chengmo@localhost ~]$ awk 'BEGIN{tB["a"]="a1";tB["b"]="b1";if(tB["c"]!="1"){print "no found";};for(k in tB){print k,tB[k];}}'?
no found
a a1
b b1
c?
以上出現奇怪問題,tB[“c”]未定義,可是循環時候,發現已經存在該鍵值,它的值為空,這里須要注意,awk數組是關聯數組,僅僅要通過數組引用它的key,就會自己主動創建改序列.
?
正確推斷方法:
[chengmo@localhost ~]$ awk 'BEGIN{tB["a"]="a1";tB["b"]="b1";if( "c" in tB){print "ok";};for(k in tB){print k,tB[k];}}'??
a a1
b b1if(key in array) 通過這個方法推斷數組中是否包括”key”鍵值。
?
刪除鍵值:
[chengmo@localhost ~]$ awk 'BEGIN{tB["a"]="a1";tB["b"]="b1";delete tB["a"];for(k in tB){print k,tB[k];}}'?????????????????????
b b1?
delete array[key]能夠刪除,相應數組key的,序列值。
?
三、二維數組使用(多維數組使用)
awk的多維數組在本質上是一維數組,更確切一點,awk在存儲上并不支持多維數組。awk提供了邏輯上模擬二維數組的訪問方式。例 如,array[2,4] = 1這種訪問是同意的。awk使用一個特殊的字符串SUBSEP (\034)作為切割字段,在上面的樣例中,關聯數組array存儲的鍵值實際上是2\0344。
?
相似一維數組的成員測試,多維數組能夠使用 if ( (i,j) in array)這種語法,可是下標必須放置在圓括號里。
相似一維數組的循環訪問,多維數組使用 for ( item in array )這種語法遍歷數組。與一維數組不同的是,多維數組必須使用split()函數來訪問單獨的下標分量。split ( item, subscr, SUBSEP)?
[chengmo@localhost ~]$ awk 'BEGIN{
for(i=1;i<=9;i++)
{
? for(j=1;j<=9;j++)??
? {
tarr[i,j]=i*j;
print i,"*",j,"=",tarr[i,j];
? }
}
}'
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
1 * 6 = 6……
能夠通過array[k,k2]引用獲得數組內容.
?
方法二:
[chengmo@localhost ~]$ awk 'BEGIN{
for(i=1;i<=9;i++)
{
? for(j=1;j<=9;j++)??
? {
tarr[i,j]=i*j;
? }
}
for(m in tarr)??????????????
{
split(m,tarr2,SUBSEP);
print tarr2[1],"*",tarr2[2],"=",tarr[m];
}
}'
?
以上是awk對數組的處理相關,希望對大家實用