首页 > 代码库 > grep Demo

grep Demo

  最近在学习Linux的几个非常强大的命令awk, sed, grep. 之前对这些命令只是有非常皮毛的了解.

最近稍微深入的对这些命令进行一些学习.sed的主要功能如下:

  @1: 正则匹配某个字符串.

  @2: grep具备递归搜索文件/目录功能.

#!/bin/bash#File: grepDemo.sh#Author: lxw#Time: 2014-08-21#Usage: Demonstration for grep.main(){    #The following 2 lines are identical.    grep "seven" test.txt|wc -l    grep "seven" test.txt -c    #-c: count the number of lines(not words) that contain "seven")    #Match everything.    grep ".*" test.txt --color    #-w: word.Match the word.    grep -w "seven" test.txt --color    #\<seven: words begin with "seven"    grep "\<seven" test.txt --color    grep "seven\>" test.txt --color    #^seven: lines(not words) begin with "seven"    grep "^seven" test.txt --color    grep "seven$" test.txt --color    #-C num: print num lines around the matched line.    grep -C 1 "twentyseven" test.txt --color    #-A num: print num lines after the matched line.    grep -A 1 "twentyseven" test.txt --color    #-B num: print num lines before the matched line.    grep -B 1 "twentyseven" test.txt --color    #-E: extended-regexp.    -E is essential here. The 2nd method is better.    grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" /etc/resolv.conf  --color    grep -E "\b[0-9]{1,3}(\.[0-9]{1,3}){3}\b" /etc/resolv.conf  --color    #-v: invert-match. Print the non-matching lines.    grep -E "\b[0-9]{1,3}(\.[0-9]{1,3}){3}\b" /etc/resolv.conf | grep -v "#" --color    #-o: only-matching. Print only the matched parts, with each part on a single line.    grep -oE "\b[0-9]{1,3}(\.[0-9]{1,3}){3}\b" /etc/resolv.conf --color    #|: or.    vmstat|grep -E "procs|swpd" --color    #[:upper:] upper alphabets. [:digit:] numbers 0-9.    grep "[[:upper:]]" test.txt    --color    grep "[[:digit:]]" test.txt --color    #Find the lines that contains six/seven/eight more than once.    #NOTE:parenthesis is essential here. Otherwise, what do you think of "\1"?    grep -E "(six|seven|eight).*\1" test.txt --color    #-r:recursive    -i:ignore-case    -n:line number    grep -rin "lxw" /home/lxw/Documents/ShellScript --color}main

其中test.txt的内容如下:

one two threeseven eight one eight threethirteen fourteen fifteen sixteen seventeen eighteen sevensixteen seventeen eighteen        twenty sevenone 504 oneone 503 oneone     504     oneone     504 one#comment UPtwentyseven        #comment downtwenty1twenty3twenty5twenty7

 

Reference:

grep是什么?怎么用?http://blog.jobbole.com/75410/#comment-61666