欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

grep 仅显示匹配的字符

程序员文章站 2022-07-12 14:12:38
...
默认情况下grep会显示匹配了正则的整行,但是我们的正则只想显示匹配了的字符时怎么办



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

[quote]

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
[/quote]

[url=http://*.com/questions/1546711/can-grep-show-only-words-that-match-search-pattern]Can grep show only words that match search pattern?[/url]

于是,就有了,查看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选项,支持扩展的正则表达式,支持或“|”操作