awk內置字符串函數:實例

awk內置字符串函數
gsub(r,s)       在整個$0中用s替代r
gsub(r,s,t)     在整個t中用s替代r
index(s,t)      返回s中字符串t的第一位置
length(s)       返回s長度
match(s,r)      測試s是否包含匹配r的字符串
split(s,a,fs)   在fs上將s分成序列a
sprint(fmt,exp) 返回經fmt格式化後的exp
sub(r,s)        用$0中最左邊最長的子串代替s
substr(s,p)     返回字符串s中從p開始的後綴部分
substr(s,p,n)   返回字符串s中從p開始長度爲n的後綴部分
依次舉例:
[root@codfei5 Bash]# cat test.txt
M.Tansley       05/99   48311   Green   8       40      44
J.Lulu          06/99   48317   green   9       24      26
P.Bunny         02/99   48      Yellow  12      35      28
J.Troll         07/99   4842    Brown-3 12      26      26
L.Tansley       05/99   4712    Brown-2 12      30      28
[root@codfei5 Bash]# awk 'gsub(4842,4899){print $0}' test.txt
J.Troll         07/99   4899    Brown-3 12      26      26
[root@codfei5 Bash]# awk 'BEGIN{print index("Bunny","ny")}'
4
[root@codfei5 Bash]# awk '$1=="J.Troll"{print length($1)}' test.txt
7
[root@codfei5 Bash]# awk 'BEGIN {print length("codfei is handsome")}'
18
[root@codfei5 Bash]# awk 'BEGIN {print match("ANCD",/C/)}'
3
[root@codfei5 Bash]# awk 'BEGIN {print split("123-456-789--",array,"-")}'
5
[root@codfei5 Bash]# cat test.txt|awk 'sub(26,29)'
J.Lulu          06/99   48317   green   9       24      29
J.Troll         07/99   4842    Brown-3 12      29      26
#匹配每行第一個26
[root@codfei5 Bash]# awk '$1=="L.Tansley" {print substr($1,1,5)}' test.txt
L.Tan
#上面例子中,指定在域1的第一個字符開始,返回其前面5個字符。
[root@codfei5 Bash]# awk '$1=="L.Tansley" {print substr($1,3,99)}' test.txt
Tansley
#如果給定長度值遠大於字符串長度,awk將從起始位置返回所有字符,要抽取 L.Tansley
#的姓,只需從第3個字符開始返回長度爲7。可以輸入長度99,awk返回結果相同。
[root@codfei5 Bash]# awk '{print substr($1,3)}' test.txt
Tansley
Lulu
Bunny
Troll
Tansley
[root@codfei5 Bash]# str="say hello to you "
[root@codfei5 Bash]# echo $str| awk '{print substr($str,1,3)}'
say
[root@codfei5 Bash]# echo $str| awk '{print substr($str,5,5)}'
hello
[root@codfei5 Bash]# echo $str| awk '{print substr($str,11,2)}'
to
[root@codfei5 Bash]# echo $str| awk '{print substr($str,14,3)}'
you
[root@codfei5 Bash]# echo $str| awk '{print substr($str,14)}'
you
[root@codfei5 Bash]# echo $str| awk '{print substr($str,11)}'
to you
[root@codfei5 Bash]# echo $str| awk '{print substr($str,5)}'
hello to you
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章