注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

随机过程

http://superware.blog.163.com

 
 
 

日志

 
 

Summary of One-line Program in AWK  

2015-01-16 15:01:58|  分类: 默认分类 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

The common pattern of a one-line program in AWK can be given as the following:

awk 'pattern { statement }' input_file

where pattern is the relationship expression or a regular expression,and the statement is the action of the program, which can be a control flow or some other statements or expressions. Although awk can be used to write programs of some complexity, many useful programs are not much more complicated than one line. Here is a collection of short programs for instructive.


1. Print the total number of input lines:

END { print NR }


2. Print the tenth input lines:

NR == 10


3. Print the last field of every input line:

{ print $NF }


4. Print the last field of the last input line:

{ field = $NF }

END { print field }


5. Print every input line with more than four fields:

NF > 4


6. Print every input line in which the last field is more than 4:

$NF > 4


7. Print the total number of fields in all input lines:

{ nf = nf + NF }

END { print nf }


8. Print the total number of lines that contain Beth:

/Beth/ { nlines = nlines + 1 }
END { print nlines}


9. Print the largest first field and the line that contains it:

$1 > max { max = $1; maxline = $0 }
END { print max, maxline }


10. Print every line that has at least one field:

NF > 0



11. Print every line longer than 80 characters:

length($0) > 80



12. Print the number of fields in every line followed by the line itself:

{ print NF, $0 }



13. Print the first two fields, in opposite order, of every line:

{ print $2, $1 }



14. Exchage the first two fields of every line and then print the line:

{ temp = $1; $1 = $2; $2 = temp; print }



15. Print every line with the first field replaced by the line number:

{ $1 = NR; print }


16. Print every line after erasing the second field:

{ $2 = " "; print }


17. Print in reverse order the fields of every line:

{

for ( i == NF; i > 0; i = i - 1) printf ("%s ", $i)
  printf ("\n")
}


18. Print the sums of the fields of every line:

{
  sum = 0
  for ( i = 1; i <= NF; i = i + 1) sum = sum + $i
    print sum
}



19. Print the sum of all fields in all lines:

{

for (i = 1; i <= NF; i = i + 1)

sum = sum + $i

}


END { print sum }


20. Print every line after replacing each field by its absolute value:

{
  for (i = 1; i <= NF; i = i + 1)
    if ( $i < 0 )

$i = -$i
  print
}

  评论这张
 
阅读(71)| 评论(0)
推荐

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017