Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can grep show only words that match search pattern?

Tags:

grep

words

Is there a way to make grep output "words" from files that match the search expression?

If I want to find all the instances of, say, "th" in a number of files, I can do:

grep "th" * 

but the output will be something like (bold is by me);

 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  

What I want it to output, using the same search, is:

the the the this thoroughly 

Is this possible using grep? Or using another combination of tools?

like image 299
Neil Baldwin Avatar asked Oct 10 '09 00:10

Neil Baldwin


People also ask

How do you grep words only?

The easiest of the two commands is to use grep's -w option. This will find only lines that contain your target word as a complete word. Run the command "grep -w hub" against your target file and you will only see lines that contain the word "hub" as a complete word.

How do you grep only the match?

Grep: Print only the words of the line that matched the regular expression, one per line. We used the following parameters on our command: -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.

What does grep return if no match?

If there's no match, that should generally be considered a failure, so a return of 0 would not be appropriate. Indeed, grep returns 0 if it matches, and non-zero if it does not.

Which of the grep command option will select non matching lines from given file?

-v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words.


1 Answers

Try grep -o:

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

Edit: matching from Phil's comment.

From the docs:

-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. 
like image 75
Dan Midwood Avatar answered Nov 17 '22 14:11

Dan Midwood