awk函数介绍

转:http://blog.163.com/njut_wangjian/blog/static/165796425201611100261205/


awk基本语法:http://www.runoob.com/linux/linux-comm-awk.html

awk文章系列,将会详细系统地介绍awk常用的用法。首先介绍最常用的字符串函数。


环境:
[root@MySQL ~]# cat /etc/issue
CentOS release 6.5 (Final)
Kernel \r on an \m
[root@MySQL ~]# awk --version
GNU Awk 3.1.7

1.asort和asorti
格式:
asort(s [, d])
asorti(s [, d]) 
功能及返回值:
asort:对数组进行排序,如果省略参数d,则修改数组s,如果提供参数d,则将数组s拷贝到d中然后进行排序,数组s不会被修改,排序后数组的下标从1开始;最终返回数组中元素个数

[root@MySQL ~]# awk 'BEGIN{a[0]="a";a[1]="c";a[2]="b";print "before sorting:";for(i in a){print i,a[i]};asort(a);print "after sorting:";for(i in a){print i,a[i]}}'
before sorting:
0 a
1 c
2 b
after sorting:
1 a
2 b
3 c


[root@MySQL ~]# awk 'BEGIN{a[0]="a";a[1]="c";a[2]="b";print "before sorting:";for(i in a){print i,a[i]};asort(a,d);print "after sorting:";for(i in a){print i,a[i]};print ;for(i in d){print i,d[i]}}'
before sorting:
0 a
1 c
2 b
after sorting:
0 a
1 c
2 b

1 a
2 b
3 c


2.sub、gensub和gsub函数
格式:
sub(r, s [, t])
gsub(r, s [, t])
gensub(r, s, h [, t])
功能及返回值:
sub:对于t中匹配r的字串,将第一个匹配的子串替换为s,如果t省略,则t为$0;返回值为替换的字符串个数
gsub: 对于t中匹配r的字串,将匹配的所有子串替换为s, 如果t省略,则t为$0; 返回值为替换的字符串个数
gensub: 对于t中匹配r的字串,如果h是以"g"或"G"开头的字符串,则 将匹配的所有子串替换为s,如果h是数字n,则将第n处匹配进行替换;如果参数t省略, 则t为$0
sub及gsub案例

[root@MySQL ~]# awk 'BEGIN{r="or|ll";s="wj";t="hello,world!hello,awk";print sub(r,s,t),t}'
1 hewjo,world!hello,awk
[root@MySQL ~]# awk 'BEGIN{r="or|ll";s="wj";t="hello,world!hello,awk";print gsub(r,s,t),t}'
3 hewjo,wwjld!hewjo,awk
[root@MySQL ~]# echo "hello,world;hello,awk"|awk '{r="or|ll";s="wj";print sub(r,s),$0}'
1 hewjo,world;hello,awk
[root@MySQL ~]# echo "hello,world;hello,awk"|awk '{r="or|ll";s="wj";print gsub(r,s),$0}'
3 hewjo,wwjld;hewjo,awk

注:正则表达式另外一种写法

[root@MySQL ~]# echo "hello,world;hello,awk"|awk '{s="wj";print gsub(/or|ll/,s),$0}'
3 hewjo,wwjld;hewjo,awk

注:sub和gsub函数功能相同,前者指替换匹配的第一个字符串,而后者进行全局替换
gensub案例

#省略参数t

[root@MySQL ~]# echo "hello,world\!hello,awk\!hello linux\!"|awk 'BEGIN{s="ww";r="ll"}{print gensub(r,s,"g")}'
hewwo,world\!hewwo,awk\!hewwo linux\!


#参数h以g或G开头

[root@MySQL ~]# awk 'BEGIN{s="ww";t="hello,world!hello,awk!hello linux!";r="ll";print gensub(r,s,"g",t)}'
hewwo,world!hewwo,awk!hewwo linux!
[root@MySQL ~]# awk 'BEGIN{s="ww";t="hello,world!hello,awk!hello linux!";r="ll";print gensub(r,s,"g1",t)}'
hewwo,world!hewwo,awk!hewwo linux!
[root@MySQL ~]# awk 'BEGIN{s="ww";t="hello,world!hello,awk!hello linux!";r="ll";print gensub(r,s,"G1",t)}'
hewwo,world!hewwo,awk!hewwo linux!
[root@MySQL ~]# awk 'BEGIN{s="ww";t="hello,world!hello,awk!hello linux!";r="ll";print gensub(r,s,"g1",t)}'
hewwo,world!hewwo,awk!hewwo linux!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值