是否有一种方法使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吗?或者使用另一种工具组合?


当前回答

这比你想的要简单。试试这个:

egrep -wo 'th.[a-z]*' filename.txt #### (Case Sensitive)

egrep -iwo 'th.[a-z]*' filename.txt  ### (Case Insensitive)

在那里,

 egrep: Grep will work with extended regular expression.
 w    : Matches only word/words instead of substring.
 o    : Display only matched pattern instead of whole line.
 i    : If u want to ignore case sensitivity.

其他回答

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

Grep命令只与perl匹配

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

我对awk难以记忆的语法不满意,但我喜欢用一个实用程序来做这件事的想法。

似乎ack(或者ack-grep如果你使用Ubuntu)可以很容易地做到这一点:

# ack-grep -ho "\bth.*?\b" *

the
the
the
this
thoroughly

如果你省略-h标志,你会得到:

# ack-grep -o "\bth.*?\b" *

some-other-text-file
1:the

some-text-file
1:the
the

yet-another-text-file
1:this
thoroughly

作为奖励,你可以使用——output标志来完成更复杂的搜索,使用我发现的最简单的语法:

# echo "bug: 1, id: 5, time: 12/27/2010" > test-file
# ack-grep -ho "bug: (\d*), id: (\d*), time: (.*)" --output '$1, $2, $3' test-file

1, 5, 12/27/2010

你可以将空格转换为换行符,然后再转换为grep,例如:

cat * | tr ' ' '\n' | grep th

ripgrep

下面是使用ripgrep的示例:

rg -o "(\w+)?th(\w+)?"

它会匹配所有与th匹配的单词。