AWK擷取字串

perfychi發表於2012-09-18

AWK擷取字串

檔案file的每一行的格式如下:

600001  200712  SH  20080413

希望吧格式調整為:

600001  2007  12  2008  04  13

可以實用以下shell命令:

cat file | awk '{print $1 "\t" substr($2,1,4) "\t" substr($2,5,2) "\t" substr($4,1,4) "\t"  substr($4,5,2) "\t" substr($4,7,2)}' > newfile

 Awk substr function

Let's look at the substr function of awk.
This function has the form substr(s, a, b) and returns b number of chars from string s, starting at position a.  The parameterb is optional.
 Assume that we have a one line file called temp:
 Every good boy.
 Then, here are some substr examples:
 nawk '{print substr($1,1,1)}' temp   returns E
nawk '{print substr($1,3)}' temp   returns ery
nawk '{print substr($2,3)}' temp   returns od
nawk '{print substr($0,7,2)}' temp  returns go
分類: linux shell

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/27042095/viewspace-743984/,如需轉載,請註明出處,否則將追究法律責任。

相關文章