linux文本分析awk基础命令介绍(8)

2019-09-23 09:14:39王冬梅

sub(regex,substr,string)替换字符串string(省略时为$0)中首个出现匹配正则regex的子串substr

[root@centos7 temp]# echo 178278 world|awk 'sub(/[0-9]+/,"hello")'
hello world
[root@centos7 temp]#

gsub(regex,substr,string)与sub()类似,但不止替换第一个,而是全局替换

[root@centos7 temp]# head -n5 /etc/passwd|awk '{gsub(/[0-9]+/,"----");print $0}'   
root:x:----:----:root:/root:/bin/bash
bin:x:----:----:bin:/bin:/sbin/nologin
daemon:x:----:----:daemon:/sbin:/sbin/nologin
adm:x:----:----:adm:/var/adm:/sbin/nologin
lp:x:----:----:lp:/var/spool/lpd:/sbin/nologin

substr(str,n,m)切割字符串str,从第n个字符开始,切割m个。如果m省略,则到结尾

[root@centos7 temp]# echo "hello,世界!"|awk '{print substr($0,8,1)}'
界
[root@centos7 temp]#

tolower(str)和toupper(str)表示大小写转换

[root@centos7 temp]# echo "hello,世界!"|awk '{A=toupper($0);print A}'
HELLO,世界!
[root@centos7 temp]#

system(cmd)执行shell命令cmd,返回执行结果,执行成功为0,失败为非0

#此处if语句判断和C语言一致,0为false,非0为true
[root@centos7 temp]# awk 'BEGIN{if(!system("date>/dev/null"))print "success"}'
success
[root@centos7 temp]# 

match(str,regex)返回字符串str中匹配正则regex的位置

[root@centos7 temp]# awk 'BEGIN{A=match("abc.f.11.12.1.98",/[0-9]{1,3}./);print A}'
7
[root@centos7 temp]# 

awk作为一个编程语言可以处理各种各样的问题,甚至于编写应用软件,但它更常用的地方是命令行下的文本分析,生成报表等,这些场景下awk工作的很好。工作中如经常有文本分析的需求,那么掌握这个命令的用法将为你节省大量的时间。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。