是否有一种方法使grep从匹配搜索表达式的文件中输出“单词”?

如果我想在一些文件中找到“th”的所有实例,我可以这样做:

grep "th" *

但是输出会是这样的(粗体是我的);

some-text-file : the cat sat on the mat  
some-other-text-file : the quick brown fox  
yet-another-text-file : i hope this explains it thoroughly 

我想让它输出什么,使用相同的搜索,是:

the
the
the
this
thoroughly

这可能使用grep吗?或者使用另一种工具组合?


当前回答

grep --color -o -E "Begin.{0,}?End" file.txt

? -尽可能少的匹配直到结束

在macos终端上测试

其他回答

cat *-text-file | grep -Eio "th[a-z]+"

要搜索所有以“icon-”开头的单词,下面的命令非常有效。我在这里使用的是Ack,它类似于grep,但有更好的选项和良好的格式。

ack -oh --type=html "\w*icon-\w*" | sort | uniq

你也可以试试pcregrep。在grep中也有一个-w选项,但在某些情况下,它不能像预期的那样工作。

从维基百科:

cat fruitlist.txt
apple
apples
pineapple
apple-
apple-fruit
fruit-apple

grep -w apple fruitlist.txt
apple
apple-
apple-fruit
fruit-apple

我有一个类似的问题,寻找grep/pattern regex和“匹配的模式找到”作为输出。

最后,我使用了选项-o的egrep(相同的正则表达式在grep -e或-G上没有给我相同的egrep结果)

所以,我认为这可能是类似于(我不是一个正则表达式大师):

egrep -o "the*|this{1}|thoroughly{1}" filename

Grep命令只与perl匹配

grep -o -P 'th.*? ' filename