简体   繁体   中英

How can I search for keywords using logical AND conditions in files on Ubuntu?

I've been trying to search for multiple keyword in my Ubuntu files. I know how to do it for one file :

find /[myRep] -type f | xargs grep -rl "myFunction"

I wanted to do it for two keywords, such as myFunction and myClass , to get all the files that can instantiate myFunction in myClass .

I tryed to use :

find /[myRep] -type f | xargs grep -rl "myFunction" | xargs grep -rl "myClass"

I get results, but I'm not sure if this is accurate. Plus, I wonder if there is a simple way to add more logical conditions in the search, such as "OR", or "NOT" commands ...

Use Regex Alternation for Logical OR Conditions

If you're trying to find files that contain either "myFunction" or "myClass", you could use an extended regular expression with alternation For example:

# Using GNU Find and GNU Grep
find . exec grep --extended-regexp --files-with-matches 'myFunction|myClass' {} +

When passed a list of files to grep, this will show you matching files that contain either word.

Logical AND is Trickier

A logical AND is trickier because you have to account for ordering. You can either:

  1. Filter files on one set of requirements, then the other.
  2. Use a more full-feature program where you can store state.

As a trivial example of the first case:

# Use nulls to separate filenames for safety.
find /etc/passwd -print0 |
    xargs -0 egrep -Zl root |
    xargs -0 egrep -Zl www

As a contrived example of the second case, you could use GNU awk:

# Print name of current file if it matches both alternates
# on different lines.
find /etc/passwd -print0 |
    xargs -0 awk 'BEGIN {matches=0};
                  /root|www/ {matches+=1};
                  matches >= 2 {print FILENAME; matches=0; nextfile}'

Your command looks fine to me. You first grep all files to find those which contain "myFunction" and then pass them through another grep for "myClass". As a result, you will end up with files containing both "myFunction" and "myClass".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM