是否有一种方法使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 -w

摘自grep手册页:

-w:只选择包含完整单词的匹配行。测试是匹配的子字符串必须在行首,或者前面有一个非单词组成字符。

其他回答

只需awk,不需要组合工具。

# awk '{for(i=1;i<=NF;i++){if($i~/^th/){print $i}}}' file
the
the
the
this
thoroughly

试试grep -o:

grep -oh "\w*th\w*" *

编辑:匹配菲尔的评论。

从文档中可以看出:

-h, --no-filename
    Suppress the prefixing of file names on output. This is the default
    when there is only  one  file  (or only standard input) to search.
-o, --only-matching
    Print  only  the matched (non-empty) parts of a matching line,
    with each such part on a separate output line.

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

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.

ripgrep

下面是使用ripgrep的示例:

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

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

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

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