0x5F——shell编程学习笔记(3)

这篇主要讲grep

(1) search for the given string in a single file
grep "literal_string" filename
(2) checking for the given string in multiple files
grep "string" FILE_PATTERN
(3) Case insensitive search using grep -i
grep -i "string" FILE
(4) Match regular expression in files
grep "REGEX" filename
(5) checking for full words and case insensitive, not for sub-string using grep -w
grep -iw "string" filename
(6) displaying lines before/after/around the match
I. display N lines after match
grep -A <N> "string" FILENAME
II. display N lines before match
grep -B <N> "string" FILENAME
III. display N lines around match
grep -C <N> "string" FILENAME
(7) highlight the search using GREP_OPTIONS
export GREP_OPTIONS='--color=auto' GREP_COLOR='1;32'
grep this demo_file
(8) searching in all files recursively using grep -r
grep -r "ramesh" *
(9) invert match using grep -v
grep -v "go" demo_text
(10) display the lines which does not matches all the given pattern
grep -v -e "pattern" -e "pattern" filename
(11) counting the number of matches using grep -c
grep -c "pattern" filename
(12) display only the file names which matches the given pattern using grep -l
grep -l "this" demo_*
(13) show only the matched string
grep -o "is.*line" demo_file
(14) show the position of match in the line(byte offset of the whole line)
grep -o -b "pattern" file
(15) show line number while displaying the output using grep -n
grep -n "pattern" filename
(16)使用grep抽取精确匹配,在抽取字符串后加\>,假定在data.f里抽取48,即:
grep '48\>' data.f
(17) 用-E参数,允许使用扩展模式匹配。譬如用“或”符号
grep -E "aaa|bbb" filename
(18) grep允许使用国际字符模式匹配或匹配模式的类名形式
类 等价的正则表达式 | 类 等价的正则表达式
[[:upper:]] [A-Z]   | [[:alnum:]] [0-9a-zA-Z]
[[:lower:]] [a-z]     | [[:space:]] 空格或tab键
[[:digit:]] [0-9]      | [[:alpha:]] [a-zA-Z]
(19)用-s屏蔽错误信息,譬如本来想
grep "root" /etc/password,但实际上password不存在(应该是passwd)
于是就可以用
grep -s "root" /etc/password屏蔽错误信息,如果不支持-s(mac是支持的)也可以用
grep "root" /etc/password 2>/dev/null
(20)egrep - expression or extended grep
egrep接受所有的正则表达式,并有一个显著特性是可以以一个文件作为保存的字符串,然后将它作为egrep作为参数,为此使用-f开关。如果有一个文件grepstrings,里面内容是
pattern1
pattern2
就可以如下使用
egrep -f grepstring filename
egrep是直接支持选择'|','?'这些的,grep要加-E参数

 

posted @ 2012-06-09 22:12  cuero  阅读(212)  评论(0编辑  收藏  举报