处理文本时常有头和尾的处理需求,也有逻辑的使用,简单介绍如下
1,awk之 BEGIN 与END
BEGIN 用于需要在文本行轮询前的任务执行,END用于文档沦陷完成后的任务执行
例 找到所有bash用户,开头打印名称列,结尾打印end,并且显示每行的1,3,7列都执行左对齐,每列占10个字符的位置
-
linux-SUSE:/home/test # awk -F: 'BEGIN{print "UserName ID Shell"}$7~"bash"{printf "%-10s%-10s-%20s\n",$1,$3,$7}END{print "End of report."}' /etc/passwd
-
UserName ID Shell
-
at 25 - /bin/bash
-
bin 1 - /bin/bash
-
daemon 2 - /bin/bash
-
ftp 40 - /bin/bash
-
games 12 - /bin/bash
-
lp 4 - /bin/bash
-
man 13 - /bin/bash
-
news 9 - /bin/bash
-
nobody 65534 - /bin/bash
-
root 0 - /bin/bash
-
uucp 10 - /bin/bash
-
openlinux 1000 - /bin/bash
-
postgres 26 - /bin/bash
-
End of report.
2,awk 之 if-else 判断
例 判断文件中用户名为 root,打印列admin, 否则打印列 Common User
-
awk -F: 'BEGIN{print "UserName UserType"}{if ($1=="root") printf "%-15s: %s\n", $1,"Admin";else printf "%-15s: %s\n", $1, "Common User"}' /etc/passwd
-
UserName UserType
-
at : Common User
-
avahi : Common User
-
avahi-autoipd : Common User
-
bin : Common User
3,awk 之while 循环,
awk本身就是对文档的每一行进行遍历,while是遍历每一个字段
-
linux-SUSE:/home/test # awk -F: '{i=1;while (i<=NF) {if (length($i)>=4){print $i};i++}}' /etc/passwd
-
Batch jobs daemon
-
/var/spool/atjobs
-
/bin/bash
4,awk 之for ,
awk -F: ‘{for (i=1;i<=NF;i++) {if length($i)>=4 {print $i}}}' /etc/passwd
使用for循环实现上面的列子
-
awk -F: '{for (i=1;i<=NF;i++) {if (length($i)>=4) {print $i}}}' /etc/passwd
-
Batch jobs daemon
-
/var/spool/atjobs
-
/bin/bash
-
avahi
-
User for Avahi
-
/run/avahi-daemon
例如 awk 用for 处理统计tcp链接状态,并分开显示
-
linux-SUSE:/home/test # netstat -tan #显示当前所有tcp链接及状态
-
Active Internet connections (servers and established)
-
Proto Recv-Q Send-Q Local Address Foreign Address State
-
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN
-
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN
-
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN
-
tcp 0 0 172.18.107.223:22 172.18.107.217:51520 ESTABLISHED
-
tcp 0 0 :::22 :::* LISTEN
-
tcp 0 0 ::1:631 :::* LISTEN
-
tcp 0 0 ::1:25 :::* LISTEN
-
linux-SUSE:/home/test # netstat -tan | wc -l
-
9
-
linux-SUSE:/home/test # netstat -tan | awk '/^tcp/{STATE[$NF]++}END{for (i in STATE) {print i, STATE[i]}}'
-
LISTEN 6
-
ESTABLISHED 1
文本分析统计awk 统计文本日志中某个ip出现的次数
-
linux-SUSE:/home/test # awk '{count[$1]++}END{for (ip in count){printf "%-20s:%d\n",ip,count[ip]}}' ips.log
-
:1
-
IOError :1
-
192.168.0.1 :12
-
192.168.0.10 :1
-
192.168.0.2 :2
-
192.168.0.20 :1
-
192.168.0.11 :1
阅读(674) | 评论(0) | 转发(0) |