清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>
AWK
AKW是一个强大的文本处理工具,它的所有功能不可能在一篇文章内讲完。
本文以awk常用的几种情形作为讲解,旨在能够适用于常用的awk文本处理。
常用命令格式:
awk -F '文本切割符' '{处理过程}’ 文件名例如:awk -F ':' '{print}' file.txt
用$n表示切割后第n个部分
例如:jack:lucy:tom
用‘:’切割后,$1为jack $2为lucy $3为tom
由简单到复杂的过程如下
1、创建一个文件,方便后续操作,用last命令调出登陆信息,把最后5次的信息重定向存储到file.txt
1 2 3 4 5 6 7 8 9 | cd ~ touch file .txt last -n 5 & gt ; file .txt cat file .txt root pts/1 :0.0 Sat Sep 20 05:11 still logged in root :0 Sat Sep 20 05:11 still logged in root :0 Sat Sep 20 05:11 - 05:11 (00:00) reboot system boot 2.6.18-194.el5 Sat Sep 20 05:02 (00:10) root pts/1 :0.0 Sat Sep 20 02:03 - crash (02:59) |
2 、用默认的空白符号作为分隔符,打印分割后的第一个部分
%%注意,一定不要忘记打文件名
1 2 3 4 5 6 | awk '{print $1}' file .txt root root root reboot root |
1 2 3 4 5 6 | awk -F ' ' '{print $2}' file .txt pts/1 :0 :0 system pts/1 |
4 、用空白符作为分隔符,正则匹配开头是root的行,打印第二个部分
1 2 3 4 | awk -F ' ' '/^root/{print $2}' file .txt pts/1 :0 :0 |
5 、用空白符作为分隔符,打印开始执行的信息,正则匹配开始是root的行,打印第二个部分,打印结束执行的信息
这里的执行顺序是:BEGIN内容->每一行读取,正则匹配,切割,处理,直到读到文件末尾->END内容
1 2 3 4 5 6 7 | awk -F ' ' 'BEGIN{print "Begin..." } /^root/{print $2} END{print "End!" }' file .txt Begin... pts/1 :0 :0 pts/1 End! |
6 、用冒号作为分隔符,打印开始执行的信息,正则匹配开始是root的行,打印第二个部分,打印结束执行的信息
1 2 3 4 5 6 7 8 9 10 11 | awk -F ':' 'BEGIN{print "Begin..." } /^root/{print $2;print "one line" } END{print "End!" }' file .txt Begin... 0.0 Sat Sep 20 05 one line 0 Sat Sep 20 05 one line 0 Sat Sep 20 05 one line 0.0 Sat Sep 20 02 one line End! |