awk (一)

awk的高级部分以前没看,就先从awk开始吧,后面再重看sed

随机函数 rand ,srand

[root@x1 ~]# echo a|awk 'BEGIN{srand(PROCINFO["pid"])} {printf "%.0f\n",rand()*11}'
0
[root@x1 ~]# echo a|awk 'BEGIN{srand(PROCINFO["pid"])} {printf "%.0f\n",rand()*11}'
2
[root@x1 ~]# echo a|awk 'BEGIN{srand(PROCINFO["pid"])} {printf "%.0f\n",rand()*11}'
4
[root@x1 ~]# echo a|awk 'BEGIN{srand(PROCINFO["pid"])} {printf "%.0f\n",rand()*11}'
3

awk版随机数生成

#!/bin/sh
awk -v count=$1 -v max=$2 '
BEGIN {
  printf("this programe will genrate %d nums,between 1 to %d\n",count,max)
  for(i=1;i<=count;i++) {
    do {
        srand()
        randnum=1+int(rand()*max)
        } while (randnum in myarray)
    myarray[randnum]=randnum
     }
for(x in myarray)
  printf("%d,",myarray[x])
  print
}'

结果如下

[root@x1 ~]# ./test 6 30
this programe will genrate 6 nums,between 1 to 30
5,29,9,21,25,16,

[root@x1 ~]# ./test 6 30
this programe will genrate 6 nums,between 1 to 30
8,12,22,13,3,25,

[root@x1 ~]# ./test 5 40
this programe will genrate 5 nums,between 1 to 40
4,10,21,30,33,

字符串函数

gsub(正则,替换成,要替换的)

[root@x1 ~]# awk 'BEGIN{str="ilovelinux";re="love";gsub(re,"hate",str);print str}'  
ihatelinux
[root@x1 ~]# awk 'BEGIN{str="i love linux";re="love";gsub(re,"hate",str);print str}'  #字符串有空格也可以替换
i hate linux
[root@x1 ~]# awk 'BEGIN{str="i love linux i love you";re="love";gsub(re,"hate",str);print str}'   #可以多次替换
i hate linux i hate you
[root@x1 ~]# awk 'BEGIN{str="i love linux i love you";re="love";n=gsub(re,"hate",str);print str,n}'  #gsub()返回替换的个数
i hate linux i hate you 2

index(原串,子串)  返回子串在原串中的位置

[root@x1 ~]# awk 'BEGIN{str="ilovelinux";print index(str,"love")}'
2

split(字符串,数组,分隔符)

[root@x1 ~]# awk 'BEGIN{str="i#love#linux";split(str,array,"#");for(i in array) print array[i]}'
i
love
linux

substr(字符串,起始位置,字符个数)

[root@x1 ~]# awk 'BEGIN{str="i#love#linux";print substr(str,3,4)}'
love

单词首字母大写(awk)

awk '
BEGIN {
  upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  lower="abcdefghijklmnopqrstuvwxyz"
  }
{position=index(lower,substr($0,1,1))
  print substr(upper,position,1)substr($0,2)
}'


原文地址:https://www.cnblogs.com/txwsqk/p/2044702.html