# array[1]=get 会将get当作一个变量来看,而get没有创建并赋值,因此不输出array[1][hadoop1@hadoop1 ~]$ awk'BEGIN{array[0]=1234;array[1]=get;print array[0],array[1]}'1234# array[1]="get" 这里将get作为一个字符串赋值给数组array的第2个值即array[1][hadoop1@hadoop1 ~]$ awk'BEGIN{array[0]=1234;array[1]="get";print array[0],array[1]}'1234 get
# 遍历数组array :for (i in array) print i 这里的i是array的下标 而不是对应的值(在python中i就直接值得是相对应的值)[hadoop1@hadoop1 test]$ awk'BEGIN{array[0]=1234;array[1]="get";for (i in array) print i}'01# awk数组获取元素 array[i][hadoop1@hadoop1 test]$ awk'BEGIN{array[0]=1234;array[1]="get";for (i in array) print array[i]}'1234
get
示例:处理以下文件,将网址前缀取出并计数排序处理
# 数据[hadoop1@hadoop1 test]$ cat web.txt
http://www.etiantian.org/index.html
http://mp3.etiantian.org/1.html
http://post.etiantian.org/index.html
http://mp3.etiantian.org/2.html
http://www.etiantian.org/index.html
http://mp3.etiantian.org/3.html
# 很明显 指定分隔符// / . ;对第2列www等进行分组统计(array[]++) 最后遍历输出结果 默认不排序[hadoop1@hadoop1 test]$ awk -F"[/.]+"'{array[$2]++}END{for (i in array) print i,array[i]}' web.txt
www 2
mp3 3
post 1# 降序排列 sort -rnk2 (-k num 指定按照第num列排序; -r 降序排序,默认升序; -n 以数值型进行排序)[hadoop1@hadoop1 test]$ awk -F"[/.]+"'{array[$2]++}END{for (i in array) print i,array[i]}' web.txt |sort -rnk2
mp3 3
www 2
post 1
10.5、awk循环与判断
10.5.1、for循环
shell编程C语言for循环
for((i=1;i<10;i++));doecho$idone;awk for循环
for(i=1;i<10;i++)
print i
# 数据 a.txt
I am a student I like eating apple and playing basketball.
# 命令行筛选[hadoop1@hadoop1 test]$ awk'{for(i=1;i<NF;i++)print$i}' a.txt
I
am
a
student
I
like
eating
apple
and
playing
# length awk内置函数 用来计算字符串长度[hadoop1@hadoop1 test]$ awk'{for(i=1;i<NF;i++) if(length($i)<6) print$i}' a.txt
I
am
a
I
like
apple
and
##### 使用awk脚本筛选 a.awk#!/bin/awk -f{
for(i=1;i<=NF;i++)
if(length($i)<6)
print $i}[hadoop1@hadoop1 test]$ awk -f a.awk a.txt
I
am
a
I
like
apple
and