交叉分发安全答案(包括 windows minGW?)
grep -h "[[:alpha:]]*th[[:alpha:]]*" 'filename' | tr ' ' '\n' | grep -h "[[:alpha:]]*th[[:alpha:]]*"
如果您使用的是不包含 -o 选项的旧版本的 grep(如 2.4.2),请使用上述版本。否则使用下面更易于维护的版本。
Linux 跨发行版安全答案
grep -oh "[[:alpha:]]*th[[:alpha:]]*" 'filename'
总结一下:-oh 输出与文件内容(而不是文件名)匹配的正则表达式,就像您期望正则表达式在 vim/etc 中的工作方式一样...您会使用什么词或正则表达式寻找然后,由你决定!只要您仍然使用 POSIX 而不是 perl 语法(请参阅下文)
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 `[[:>:]]';
原来的答案并不适合所有人的原因
\w 的用法因平台而异,因为它是扩展的“perl”语法。因此,那些仅限于使用 POSIX 字符类的 grep 安装使用 [[:alpha:]],而不是其 perl 等效的 \w。 See the Wikipedia page on regular expression for more
最终,无论 grep 的平台(是原始平台)如何,上面的 POSIX 答案都会更加可靠
对于不带-o选项的grep的支持,第一个grep输出相关行,tr将空格分割成新行,最后的grep只过滤相应的行。
(PS:我知道现在大多数平台都会为 \w....
感谢@AdamRosenfield 回答的“-o”解决方法