How Do You Find Words That Match a Pattern and Not the Line with Bash?

You want to search a file for words that include a given pattern. You want to use grep to return the word that matches a pattern, and you do not want to return the entire line that matches a pattern. You want to return the exact word without the leading space or trailing space. What do you do?

Try this command:

cat foobar.txt | tr "//" "\n" | grep "coolpattern"

The above, specifically the tr command and flags, will introduce new lines for every space. You may need to pipe the output to an awk (e.g., | awk '{print $2}' ).

Leave a comment

Your email address will not be published. Required fields are marked *