Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3854009
  • 博文数量: 146
  • 博客积分: 3918
  • 博客等级: 少校
  • 技术积分: 8584
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-17 13:52
个人简介

个人微薄: weibo.com/manuscola

文章分类

全部博文(146)

文章存档

2016年(3)

2015年(2)

2014年(5)

2013年(42)

2012年(31)

2011年(58)

2010年(5)

分类: LINUX

2012-12-14 00:11:00

    平时工作写过一些shell脚本,掌握了一些shell命令,也看过两本shell编程的书,但是对shell的熟练程度还是不够。总体而言就是练习还是不够,所以不能运用自如。我决定经常练习写一些的shell 代码,习惯用shell 命令来解决一些问题。


1  采用grep
grep 里面有个 -o 选项,这个选项我还真不知道,今天看了一篇博文,才知道有这个选项。

  1. -o, --only-matching
  2.    Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
就是把匹配到的模式,打印出来,每次匹配,都会换行。

  1. cat test.txt
  2. manu is good boy, manu study linux kernel
  3. manu is in nanjing
  1. grep -o manu test.txt
  2. manu
  3. manu
  4. manu

  5. grep -o manu test.txt |wc -l
  6. 3

2 awk
awk 里面有个函数叫做gsub,可以理解为global substitude, 全局替换。这个函数会返回找到的个数:

  1. root@manu:~/code/shell # awk  '{s+=gsub(/manu/,"manuscola"); print }END{print s}'  test.txt
    manuscola is good boy, manuscola study linux kernel
    manuscola is in nanjing
    3
我将test.txt文件里面的manu 统统换成manuscola,同时统计出现的个数。
这样的话,我们就得到了第二个方法:



  1. awk '{s+=gsub(/字符串/,"")}END{print s}' file

    当然这个题目有很多其他的办法。掌握更多的命令的用法,做大量的练习,最终达到运用自如的程度

参考文献:
The AWK Manual

2   man grep

阅读(6356) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~