Shell08awk高级用法 [操作系统入门]
1. 指定宽度对齐说明:
%-30s表示输出字符串,宽度30位,左对齐.%-15s用来指定第二列的,左对齐,宽度15.两个百分号之间可以没有空格.
使用
对每一行的输出加上换行符。
work]
# awk -F: ‘{print "user:" $1" uid:" $3}‘ /etc/passwd | awk ‘{printf "%-30s%-15s",$1,$2}‘ | head -5
user:root uid:0
user:bin uid:1
user:daemon uid:2
user:adm uid:3
user:lp uid:4
2. 求1-100的和
work]# awk ‘BEGIN{for(i=0;i<=100;i++)s+=i;print("1-100的和是:"s,s>5000?"大于5000":"小于等于5000")}‘
1-100的和是:5050 大于5000
3. ifelse ~ && 的使用
work]# awk ‘BEGIN{a="100testaaa";if(a~/100/&&a~/test/){print "包含100和test"}else{print "不包含100和test"}}‘
包含100和test
4. for 循环
原数据:
work]# netstat -an | awk ‘/^tcp/{print $0}‘
tcp 0 0 0.0.0.0:999 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:5355 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN
tcp 0 0 192.168.4.159:22 113.140.6.182:2240 ESTABLISHED
tcp 0 0 192.168.4.159:50644 100.100.30.26:80 ESTABLISHED
tcp 0 48 192.168.4.159:22 113.140.6.182:2238 ESTABLISHED
tcp 0 0 192.168.4.159:49328 100.100.99.23:443 TIME_WAIT
tcp6 0 0 :::5355 :::* LISTEN
tcp6 0 0 :::80 :::* LISTEN
处理后:
work]# netstat -an | awk ‘/^tcp/{++s[$NF]}END{for(a in s)print a,s[a]}‘
LISTEN 5
ESTABLISHED 3
TIME_WAIT 1
5. 字符串替换 gsub( Ere, Repl, [ In ] ) || sub( Ere, Repl, [ In ] )
work]# awk ‘BEGIN{info="My phone number is 131-5209-8678";gsub(/[0-9]{4,}/,"xxxx",info);print tolower(info)}‘
my phone number is 131-xxxx-xxxx
6. 字符串查找 存在则返回首次出现的位置,不存在返回0 index( String1, String2 )
work]# echo "bb aabccbb" | awk ‘{print index($2,$1)}‘
6
work]# echo "ff aabccbb" | awk ‘{print index($2,$1)}‘
0
7. 大小写转换 及 字符串长度
work]# echo "aa BBCC" | awk ‘{print toupper($1),tolower($2),length($2)}‘
AA bbcc 4
8. 字符串截取 substr( String, M, [ N ] )
work]# awk ‘BEGIN{info="123456789";print substr(info,4,5);}‘
45678
9. 字符串匹配 match( String, Ere )
work]# awk ‘BEGIN{info="aaa456bbb";print match(info,/[0-9]+/)}‘
4
work]# awk ‘BEGIN{info="aaabbb";print match(info,/[0-9]+/)}‘
0
work]# awk ‘BEGIN{info="aaa456bbb";print match(info,/[0-9]+/)?"ok":"not found";}‘
ok
10. 字符串分割 split( String, A, [Ere] )
work]# awk ‘BEGIN{info="aaa#456#bbb";split(info,res,"#");print length(res);for(i in res){print i,res[i]}}‘
3
1 aaa
2 456
3 bbb
Shell 08 awk高级用法
以上是 Shell08awk高级用法 [操作系统入门] 的全部内容, 来源链接: utcz.com/z/519516.html