您的位置:首页 > 其它

AWK 高端大气上档次

2014-03-29 13:15 162 查看
首先认识一下 将默认的空格换成制表符分割,或者其他形式的分割没做任何改变前:[root@g script]# awk -F, '{print $1,$2,$3}' example101 jesn Doe CEO102 Jason Smith IT Manager103 Raj Reddy Sysadmin104 Anand Ram Developer105 Jane Miller Sales Manager做了改变后:[root@g script]#[root@g script]# awk 'BEGIN{FS=","; OFS="\t"}{print $1,$2,$3}' example101 jesn Doe CEO102 Jason Smith IT Manager103 Raj Reddy Sysadmin104 Anand Ram Developer105 Jane Miller Sales ManagerBEGIN是预处理,那么就可以在预处理的时候将打印一些文件,注意类似c语言,要在借宿加上分号[root@g script]# awk 'BEGIN{FS=","; OFS="\t"; print "========"}{print $1,$2,$3}' example========101 jesn Doe CEO102 Jason Smith IT Manager103 Raj Reddy Sysadmin104 Anand Ram Developer105 Jane Miller Sales Manager[root@g script]# awk 'BEGIN{FS=","; OFS="\t"; print "========"}{print $1,$2,$3} END{print "+++++++++++"}' example========101 jesn Doe CEO102 Jason Smith IT Manager103 Raj Reddy Sysadmin104 Anand Ram Developer105 Jane Miller Sales Manager+++++++++++1:可以处理多种分隔符:现在原文是这样101,jesn Doe%CEO102,Jason Smith:IT Manager103,Raj Reddy;Sysadmin104,Anand Ram,Developer105,Jane Miller,Sales Manager则现在文中既有逗号,百分号,冒号,引号分割的那处理起来就是这样[root@g script]#[root@g script]# awk 'BEGIN{FS="[,%:;]";OFS="\t"}{print $1,$2,$3}' example101 jesn Doe CEO102 Jason Smith IT Manager103 Raj Reddy Sysadmin104 Anand Ram Developer105 Jane Miller Sales Manager2:指定分隔符,并换行主要是用RS处理 (RS 的作用是制定换行的符号;)原文件是这样[root@g script]# cat tmp103Raj ReddySysadmin-104Anand RamDeveloper-105Jane MillerSales Manager这里我们可以将\n 作为一个预分割符FS,则整个数据文件相当于一行,那么输出要求是以;区分开,则OFS就是 ; 那么显然这里要用到RS,RS就是很显然用 -\n 作为分割符 则就分成了3行,然后打印出 文件就可以了处理后:[root@g script]#[root@g script]# awk 'BEGIN{FS="\n";OFS=":";RS="-\n"}{print $1,$2,$3}' tmp103:Raj Reddy:Sysadmin104:Anand Ram:Developer105:Jane Miller:Sales Manage3:win文件和linux文件互转的格式变化首先win文件是以/r/n作为一行的借宿, 而 linux 则是以/n作为一行的结束;现在讲linux 下文件传到 win下则是使用RS=“/n” ORS="/r/n" 即可如果是win下向linux下穿文件则反过来就可以4:NR内置变量:打印行号 FILENAME 文件名[root@g script]# awk '/John/ {print NR,$0}' example1 101,John Doe,CEO[root@g script]# awk '/John/ {print FILENAME, NR,$0}' exampleexample 1 101,John Doe,CEONR第二个牛逼的作用是作为匹配次数来用:[root@g script]# awk '/10/{print NR,$0 }END{ print "the sum NUmber is " NR}' example1 101,John Doe,CEO2 102,Jason Smith,IT Manager3 103,Raj Reddy,Sysadmin4 104,Anand Ram,Developer5 105,Jane Miller,Sales Managerthe sum NUmber is 5
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息