grep 仅显示匹配的字符

默认情况下grep会显示匹配了正则的整行,但是我们的正则只想显示匹配了的字符时怎么办


grep -oh "[[:alpha:]]*th[[:alpha:]]*" 'filename'

引用


This is an updated and cross distribution safe answer

grep -oh "[[:alpha:]]*th[[:alpha:]]*" 'filename'

To summaries -oh outputs the regular expression matches to the file content (and not its filename), just like how you would expect regular expression to work in vim/etc... What word or regular expression you would be searching for then, is up to you! As long as you remain to POSIX and not perl syntax (refer below)

More from the manual for grep

-o      Print each match, but only the match, not the entire line.
-h      Never print filename headers (i.e. filenames) with output lines.
-w      The expression is searched for as a word (as if surrounded by
         `[[:<:]]' and `[[:>:]]';

The reason why the original answer does not work for everyone


Can grep show only words that match search pattern?

于是,就有了,查看weblogic GC日志的命令

在多个weblogic服务器日志上找FullGC
//查找FullGC
grep 'Full' `head -n 10  weblogic.log |grep -oh 'gc_.*log'` 


查找日志末5000行,打印文件名和错误的行
tail -n 50000  */weblogic*.log  |grep -E "weblogic.*log|2937u38338"

-E选项,支持扩展的正则表达式,支持或“|”操作

猜你喜欢

转载自powertech.iteye.com/blog/2185326