码迷,mamicode.com
首页 > 其他好文 > 详细

awk常见基本使用

时间:2017-02-26 22:11:11      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:strong   匹配   bsp   log   size   cat   等于   打印   常见   

-F 指定分割符号

[root@bogon ~]# cat 1.txt 
a:b:c:d
a1:b1:c1:d1
a2:b2:c2:d2
a_: :c:dddd
[root@bogon ~]# awk -F : {print $1} 1.txt 
a
a1
a2
a_
[root@bogon ~]# awk -F : {print $2} 1.txt 
b
b1
b2
[root@bogon ~]# awk -F : {print $1,$4} 1.txt 
a d
a1 d1
a2 d2
a_ dddd

匹配第三列含有数字的
awk -F ‘:‘ ‘$3~/[0-9]/‘ 1.txt
$0 表示整行
~ 模糊匹配
== 精准匹配
匹配第三列含有数字只显示第一列和第三列
awk -F ‘:‘ ‘$3~/[0-9]/ {print $1,$3}‘ 1.txt
重新指定分割符 OFS要放在前面 打印出的不能是$0
awk -F ‘:‘ ‘$3~/[0-9]/ {OFS="#";print $1,$3}‘ 1.txt
awk -F ‘:‘ ‘$1=="a2"||NR>3 {print $0}‘ 1.txt
NR 行号
NF 被分割后的列数
||或者 ,&& 且
第一段等于a2或者 行号>3的结果

[root@bogon ~]# awk -F : $3~/[0-9]/ 1.txt 
a1:b1:c1:d1
a2:b2:c2:d2
[root@bogon ~]# awk -F : $3~/[0-9]/ {print $1,$3}  1.txt 
a1 c1
a2 c2
[root@bogon ~]# awk -F : $3~/[0-9]/ {OFS="#";print $1,$3} 1.txt 
a1#c1
a2#c2

精准匹配
字符必须加引号

awk -F ‘:‘ ‘$1=="a2" {print $0}‘ 1.txt

[root@bogon ~]# awk -F : $1=="a2" {print $0} 1.txt
a2:b2:c2:d2
[root@bogon ~]# awk -F : $1=="a2"||NR>3 {print $0} 1.txt
a2:b2:c2:d2
a_: :c:dddd
表达式 
[root@bogon ~]# awk -F : $1=$2$3 {print $0}  1.txt 
bc b c d
b1c1 b1 c1 d1
b2c2 b2 c2 d2
 c   c dddd

查找分割后 列数 是3到5个的
awk -F ‘:‘ ‘NF>=3&&NF<=5 {print}‘ 1.txt

[root@bogon ~]# cat 1.txt 
a:b:c:d
a1:b1:c1:d1
e:f
e1:f1:g1
e2:f2:g2:h2:i:j:k
[root@bogon ~]# awk -F : NF>=3&&NF<=5 {print} 1.txt 
a:b:c:d
a1:b1:c1:d1
e1:f1:g1

awk -F ‘:‘ ‘{OFS="#";print $NR,$NF}‘  1.txt

[root@bogon ~]# cat 1.txt 
a:b:c:d
a1:b1:c1:d1
e:f
e1:f1:g1
e2:f2:g2:h2:i:j:k
[root@bogon ~]# awk -F : {OFS="#";print $NR,$NF}  1.txt
a#d
b1#d1
#f
#g1
i#k

对于以上 $NR,$NF的解析
1,4
2,4
3,4
4,3
5,7

 

awk常见基本使用

标签:strong   匹配   bsp   log   size   cat   等于   打印   常见   

原文地址:http://www.cnblogs.com/HKUI/p/6446114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!