Can grep show only words that match search pattern?

前端 未结 14 1640
忘掉有多难
忘掉有多难 2020-11-22 14:35

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

相关标签:
14条回答
  • 2020-11-22 15:09
    cat *-text-file | grep -Eio "th[a-z]+"
    
    0 讨论(0)
  • 2020-11-22 15:10

    grep command for only matching and perl

    grep -o -P 'th.*? ' filename
    
    0 讨论(0)
  • 2020-11-22 15:10

    You can also try pcregrep. There is also a -w option in grep, but in some cases it doesn't work as expected.

    From Wikipedia:

    cat fruitlist.txt
    apple
    apples
    pineapple
    apple-
    apple-fruit
    fruit-apple
    
    grep -w apple fruitlist.txt
    apple
    apple-
    apple-fruit
    fruit-apple
    
    0 讨论(0)
  • It's more simple than you think. Try this:

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

    Where,

     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.
    
    0 讨论(0)
  • 2020-11-22 15:14

    I had a similar problem, looking for grep/pattern regex and the "matched pattern found" as output.

    At the end I used egrep (same regex on grep -e or -G didn't give me the same result of egrep) with the option -o

    so, I think that could be something similar to (I'm NOT a regex Master) :

    egrep -o "the*|this{1}|thoroughly{1}" filename
    
    0 讨论(0)
  • 2020-11-22 15:17

    ripgrep

    Here are the example using ripgrep:

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

    It'll match all words matching th.

    0 讨论(0)
提交回复
热议问题