How to do a non-greedy match in grep?

后端 未结 7 2052
深忆病人
深忆病人 2020-11-30 17:30

I want to grep the shortest match and the pattern should be something like:


...
...
...

... mean

相关标签:
7条回答
  • 2020-11-30 17:58

    Sorry I am 9 years late, but this might work for the viewers in 2020.

    So suppose you have a line like "Hello my name is Jello". Now you want to find the words that start with 'H' and end with 'o', with any number of characters in between. And we don't want lines we just want words. So for that we can use the expression:

    grep "H[^ ]*o" file
    

    This will return all the words. The way this works is that: It will allow all the characters instead of space character in between, this way we can avoid multiple words in the same line.

    Now you can replace the space character with any other character you want. Suppose the initial line was "Hello-my-name-is-Jello", then you can get words using the expression:

    grep "H[^-]*o" file
    
    0 讨论(0)
提交回复
热议问题