开发者

Grep regular expression to find words in any order

开发者 https://www.devze.com 2023-03-04 11:14 出处:网络
Context: I want to find a class definition within a lot of source code files, but I do not know the ex开发者_高级运维act name.

Context: I want to find a class definition within a lot of source code files, but I do not know the ex开发者_高级运维act name.

Question: I know a number of words which must appear on the line I want to find, but I do not know the order in which they will appear. Is there a quick way to look for a number of words in any order on the same line?


For situations where you need to search on a large number of words, you can use awk as follows:

awk "/word1/&&/word2/&&/word3/" *.c

(If you are a cygwin user, the command is gawk.)


If you're trying to find foo, bar, and baz, you can just do:

grep foo *.c | grep bar | grep baz

That will find anything that has all three in any order. You can use word boundaries if you use egrep, otherwise that will match substrings.


While this is not an exact answer your grep question, but you should check the "ctags" command for generating tags file from the source code. For the source code objects this should help you a much more than an simple grep. check: http://ctags.sourceforge.net/ctags.html


Using standard basic regex recursively match starting from the current directory any .c file with the indicated words (case insesitive, bash flavour):

grep -r -i 'word1\|word2\|word3' ./*.c

Using standard extended regex:

grep -r -i -E 'word1|word2|word3' ./*.c

You can also use perl regex:

grep -r -i -P 'word1|word2|word3' ./*.c


If you need to search with a single grep command (for example, you are searching for multiple pattern alternatives on stdin), you could use:

grep -e 'word1.*word2' -e 'word2.*word1' -e 'alternative-word'

This would find anything which has word1 and word2 in either order, or alternative-word.

(Note that this method gets exponentially complicated as the number of words in arbitrary order increases.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号