天天看點

awk之match函數 - 青萍,你好

awk之match函數

功能:match函數是用于個性化定制搜尋模式。

例子:

   檔案内容:

this is wang ,not wan

that is chen, not che 

this is chen ,and wang ,not wan che 

  思路:

比如你想提取is後面的第一個單詞,和not 後面的第一個單詞,

這時候利用位置來提取是不可行的,因為第三行的模式和前兩行不一緻,這種情況在基因注解裡經常會碰到。

這是就可以用awk的match函數啦!!

[wangjq@mgmt humandb]$ cat test
this is wang,not wan
that is chen,not che 
this is chen,and wang,not wan che 
[wangjq@mgmt humandb]$ awk \'{match($0,/.+is([^,]+).+not(.+)/,a);print a[1],a[2]}\' test
 wang  wan
 chen  che 
 chen  wan che 
      

格式:match(string,regexp,array)  和string~regexp的作用類似

沒有array的情況下:通過regexp,在string中尋找最左邊,最長的substring,傳回substring的index位置。

有array的情況下:在regexp中用()将要組成的array的内容按順序弄好,a[1]代表第一個()的内容,a[2]代表第二個()的内容,以此類推。

echo "gene_type  "mrna";gene_name "typ""|awk \'match($0,/(gene_type).+(".+?");gene_name/,a){print a[1]}\'
gene_type

echo "gene_type  "mrna";gene_name "typ""|awk \'match($0,/(gene_type).+("+?");gene_nae/,a){print a[2]}\'
mrna