awk(三)函數

來源:互聯網
上載者:User

標籤:字串

函數是一個獨立計算的過程,它接收一些參數並返回一些值

awk有很多內建函數,分為:算術函數和字串函數

算術函數

cos(x) 返回x的餘弦(x為弧度)
exp(x)
返回e的x次冪
int(x)
返回x的整數部分的值
log(x)
返回x的自然對數(以e為底)
sin(x)
返回x的正弦(x為弧度)
sqrt(x)
返回x
atan2(y,x)
返回y/x的反正切,其值在-180度到180度之間
rand()
返回隨機數r,其中0<=r<1
srand(x) 建立rand()的新的種子數,如果沒有指定種子數目,就用當天的時間。返回舊的種子數

算術函數一共有9個,常用的也就3個。

int(x)

[email protected]:~/sedAawk/awk# awk ‘BEGIN{print int(100/3)}‘33

rand()和srand(x)

這兩個函數經常會配合使用

樓主測試了下,rand()在gawk和mawk中,是有區別的。看個例子

lrwxrwxrwx 1 root 0 4 Mar 23  2013 /bin/awk -> gawk[[email protected] ~]# awk ‘BEGIN{print rand();srand();print rand()}‘0.2377880.145391[[email protected] ~]# awk ‘BEGIN{print rand();srand();print rand()}‘0.2377880.47599
[email protected]:~/sedAawk/awk# ls -l /usr/bin/awk lrwxrwxrwx 1 root root 21 Jun 24 19:50 /usr/bin/awk -> /etc/alternatives/awk[email protected]:~/sedAawk/awk# ls -l /etc/alternatives/awklrwxrwxrwx 1 root root 13 Jun 24 19:50 /etc/alternatives/awk -> /usr/bin/mawk[email protected]:~/sedAawk/awk# awk ‘BEGIN{print rand();srand();print rand()}‘0.8760080.876008[email protected]:~/sedAawk/awk# awk ‘BEGIN{print rand();srand();print rand()}‘0.2706220.270622

注意:mawk中,預設就是用srand()之後的種子。所以rand()的傳回值是變化。。。而gawk中,未執行srand()的時候,rand()的種子是不變的,所以看到前後兩次未執行srand()的時候,rand()的傳回值均為0.237788


字串函數

gsub(r,s,t) 在字串t中,用字串s替換和Regexr匹配的所有字串。返回替換的個數,如果沒有給出t,預設為$0。。。。在gawk中和mawk中使用,有點區別
index(s,t)
返回子串t在字串s中的位置,如果沒有指定s,則返回0
length(s)
返回字串s的長度,當沒有給出s時,返回$0的長度
match(s,r)
如果Regexr在s中出現,則返回出現的起始位置。如果s中未發現r,則返回0。設定RSTART和RLENGTH的值
split(s,a,sep)
使用欄位分隔符號sep將字串s分解到數組a的元素中,返回元素的個數。如果沒有給出sep,則使用FS。數組分隔和欄位分隔採用同樣的方式
sprintf("fmt",expr)
對expr使用printf格式說明
sub(r,s,t)
在字串t中用s替換Regexr的最初相符。如果成功則返回1,否則返回0,如果沒有給出t,則預設為$0。。。。在gawk中和mawk中使用,有點區別
substr(s,p,n)
返回字串s中從位置p開始,最大長度為n的子串,如果沒有給出n,返回p開始的所有的字串
tolower(s)
將字串s中所有大寫字元轉換為小寫,並返回新串
toupper(s)
將字串s中所有小寫字元轉換為大寫,並返回新串

sprintf("fmt",expr)

sprintf()和printf使用相同的格式說明,不同的地方是,printf把結果直接列印到終端。而sprintf則不會列印結果,而是可以把結果賦值給變數

看個例子

[email protected]:~/sedAawk/awk# awk ‘BEGIN{sprintf("c",100)}‘[email protected]:~/sedAawk/awk# awk ‘BEGIN{a=sprintf("c",100);print a}‘c

字串處理[index(s,t),substr(s,p,n)]

index(s,t)返回子串t在字串s中首次出現的位置

[email protected]:~/sedAawk/awk# awk ‘BEGIN{print index("222111","1")}‘4

substr(s,p,n)有點類似python中的序列的切片。

注意:p開始的n個字元,是包括p位置的字元的

[email protected]:~/sedAawk/awk# awk ‘BEGIN{print substr("asdfghj",2,3)}‘sdf[email protected]:~/sedAawk/awk# awk ‘BEGIN{print substr("asdfghj",2)}‘sdfghj

length(s)

返回字串的長度。不指定s,則預設為$0

[email protected]:~/sedAawk/awk# awk ‘BEGIN{print length("211212")}‘6[email protected]:~/sedAawk/awk# awk ‘{print length()}‘ test1111

替換函數[sub(r,s,t),gsub(r,s,t)]

sub和gsub的區別,是sub只實現第一個位置的替換,而gsub則實現所有位置的替換。

注意:

1.如果沒指定t,則預設為$0

2.sub和gsub返回的不是替換後的字串,而是替換的次數。   字串t會被改變,可以列印t得到替換後的結果

3.替換字串中如果有&,則表示和前面的Regex對於。和sed中的類似

注意這兩個函數在gawk中和mawk中,使用是有些區別的。gawk中可以正常使用,而mawk中則有點問題

[email protected]:~/sedAawk/awk# awk ‘BEGIN{sub(/2/,"asd","22")}‘awk: line 1: syntax error at or near 22[email protected]:~/sedAawk/awk# awk ‘BEGIN{A="22";a=gsub(/2/,"&qwer",A);print A,a}‘2qwer2qwer 2

大小寫轉換[tolower(s),toupper(s)]

[email protected]:~/sedAawk/awk# echo "HeLlo"|awk ‘{printf("<%s>,<%s>\n",tolower($0),toupper($0))}‘<hello>,<HELLO>

match(s,r)

注意

1.match(s,r)和index(s,t),這兩個函數的第一個參數為字串,第二個參數為正則或子串。而其他的像sub(r,s,t),gsub(r,s,t)這兩個函數的字串是最後一個參數

2.match(s,r)返回最初相符結果的位置

3.match(s,r)有兩個相關的系統變數,RSTART,RLENGTH。。這兩個系統變數,記錄match(s,r)函數執行後的,匹配結果的起始位置,及匹配結果的長度。。。RSTART預設值為0,RLENGTH預設值為-1

match()在實際運用中,主要用於條件陳述式,迴圈,或者常式模式的條件判斷。

書上有個例子,在這裡套用一下

[email protected]:~/sedAawk/awk# cat lower awk ‘BEGIN {upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"      lower = "abcdefghijklmnopqrstuvwxyz"}{    while (match($0,/[A-Z]+/))       for (x=RSTART;x<RSTART+RLENGTH;++x){           CAP = substr($0,x,1)   CHAR = index(upper,CAP)   gsub(CAP,substr(lower,CHAR,1))       }    print $0}‘ $*

執行

[email protected]:~/sedAawk/awk# echo "Hello"| bash lower hello

自訂函數

格式:

function name(parameter-list){

    statements

    return expression

}

parameter-list是用逗號分隔的變數列表

一般函數定義在指令碼頂部,所有模式操作之前

看個例子,定義一個insert函數,可以在指定的字串的指定位置,插入指定的字串

[email protected]:~/sedAawk/awk# awk ‘function insert(STRING,POS,INS) {before_tmp = substr(STRING,1,POS)after_tmp = substr(STRING,POS+1)return before_tmp INS after_tmp}BEGIN{print insert("1234",2,"AAA")}‘12AAA34

awk中的自訂函數,也可以放到檔案中,方面管理及重用

[[email protected] ~]# awk  -f insert.awk -f  insert          12AAA34

不過樓主測了下,awk的指令碼不寫在檔案中的話,直接命令列。。好像不能用檔案中的函數。

看下面的例子

[[email protected] ~]# awk  -f insert ‘BEGIN{print insert("dfsdfsf",2,"OOOO")}‘            [[email protected] ~]# awk  ‘BEGIN{print insert("dfsdfsf",2,"OOOO")}‘ -f insertawk: fatal: function `insert‘ not defined

當然,gawk還提供了一些函數。systime(),strftime(format,timestamp)等時間相關的函數。

[[email protected] ~]# awk ‘BEGIN{print systime()}‘                    1405488653[[email protected] ~]# awk ‘BEGIN{print strftime("%Y-%m-%d %H:%M:%S")}‘2014-07-16 13:30:55

樓主的系統是Debian,預設是mawk,不支援這些時間函數





本文出自 “西風” 部落格,請務必保留此出處http://lixcto.blog.51cto.com/4834175/1438972

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.