Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep regular expression to find words in any order

Tags:

regex

grep

Context: I want to find a class definition within a lot of source code files, but I do not know the exact 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?

like image 895
Facundo Casco Avatar asked May 06 '11 18:05

Facundo Casco


People also ask

Can you use regex with grep?

Grep Regular Expression A regular expression or regex is a pattern that matches a set of strings. A pattern consists of operators, constructs literal characters, and meta-characters, which have special meaning. GNU grep supports three regular expression syntaxes, Basic, Extended, and Perl-compatible.

How do you grep 2 patterns at a time?

The basic grep syntax when searching multiple patterns in a file includes using the grep command followed by strings and the name of the file or its path. The patterns need to be enclosed using single quotes and separated by the pipe symbol. Use the backslash before pipe | for regular expressions.

How do you grep a word in a line?

To Show Lines That Exactly Match a Search String To print only those lines that completely match the search string, add the -x option. The output shows only the lines with the exact match. If there are any other words or characters in the same line, the grep does not include it in the search results.


1 Answers

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.)

like image 165
Chris Noe Avatar answered Oct 11 '22 03:10

Chris Noe