数组应用场景
数组的下标可以是任意形式,理解为高级语言的map表即可
统计次数:统计每个用户ip出现的次数,统计每种状态码出现次数,统计系统中每个用户被攻击的次数,统计攻击者ip出现的次数
求和:统计每个ip消耗的流量
shell数组 | awk数组 | |
---|---|---|
形式 | array[0]=oldboy array[1]=lidao | array[0]=oldboy array[1]=lidao |
使用 | echo ${array[0]} ${array[1]} | print array[0] array[1] |
批量输出数组的内容 | for i in ${array[*]} do echo $i done | for(i in array) print a[i] |
awk数组中取变量不用$
,awk中的$
就用来取列,$0
取一行
awk 'BEGIN{a[0]=12306; a[1]="lidao"; print a[0],a[1]}'
awk 'BEGIN{a[0]=12306; a[1]="lidao"; a[2]="hello"; a[3]=123; for(i in a) print i,a[i]};'
http://www.etiantain.org/index.html
http://www.etiantain.org/1.html
http://post.etiantain.org/index.html
http://mp3.etiantain.org/index.html
http://www.etiantain.org/3.html
http://post.etiantain.org/2.html
awk -vFS=/ '{array[$3]++;}END{for (url in array) print url, array[url]}' url.txt
awk -vFS=/ '{array[$3]++;}END{for (url in array) print url, array[url]}' url.txt | sort -rnk2
awk '$9~[0-9][0-9][0-9]/{array[$9]++}END{for (i in array) print i, array[i]}' access.log | sort -rnk2
shell循环 | awk循环 | |
---|---|---|
使用 | for(i=1;i<=10;i++) do echo $i done | for(i=1;i<=10;i++) {print i} |
awk 'BEGIN{for(i=1;i<=100;i++){sum+=i;} print sum;}'
df -h | awk -F"[ %]+" 'NR>1{if($5>20){print "disk not enough", $1, $5,$NF}}'
awk使用条件判断时,第一个条件在{动作}前,后面还有条件判断用if
Studying a subject that you feel pointless is never a fun or easy task. If you're study history, asking yourself the question "why is history important" is a very good first step. History is an essential part of human civilization. You will find something here that will arouse your interest, or get you thinking about the significance of history.
shen@ubuntu-vm:~/code/test$ awk -F"[ .\",]+" '{for(i=1;i<=NF;i++){print $i}}' en.txt
Studying
a
subject
that
you
feel
pointless
is
never
a
fun
or
easy
task
If
you're
study
history
asking
yourself
the
question
why
is
history
important
is
a
very
good
first
step
History
is
an
essential
part
of
human
civilization
You
will
find
something
here
that
will
arouse
your
interest
or
get
you
thinking
about
the
significance
of
history
shen@ubuntu-vm:~/code/test$ awk -F"[ .\",]+" '{for(i=1;i<=NF;i++){if(length($i)>6)print $i}}' en.txt
Studying
subject
pointless
history
yourself
question
history
important
History
essential
civilization
something
interest
thinking
significance
history
shen@ubuntu-vm:~/code/test$ awk -F"[ .\",]+" '{for(i=1;i<=NF;i++){if(length($i)>6) sum+=1}} END{print sum}' en.txt
16