简体   繁体   中英

Grep Multiple Things out of Order

I am currently working on creating a database in bash. I want to add an "and" function. This function will search for two things, and only return things that match both searches. How would I achieve that?

Here's my code:

#!/bin/bash

clear

#return all
function all {
    cat people.dat
}
#return some
function search {
    grep -i "$SEARCH" people.dat || echo "search returned nothing"
}
#or search
function or {
    egrep -i "$search1|$search2" people.dat
}
#and search
function and {
    if [[ $(grep -i "$search1") = $(grep -i "$search2") ]]; then
        echo yes
        #that is temporary I want to see if it worked
    fi
}
#return null
function null {
    return
}

while [ true ]
do
    #get the search
    read SEARCH

    #search
    if [[ $SEARCH == *" OR "* ]]; then
        search1=${SEARCH%" OR "*}
        search2=${SEARCH##*" OR "}
        or
    elif [[ $SEARCH == *" AND "* ]]; then
        search1=${SEARCH%" AND "*}
        search2=${SEARCH##*" AND "}
        and
    elif [ "$SEARCH" = "all" }; then
        all
    elif [ "$SEARCH" = "exit" ]; then
        exit
    elif [ "$SEARCH" = "" ]; then
        null
    else
        search
    fi
done

Pipe the output of first grep as input to second grep . Only lines with both $search1 and $search2 will be returned.

function and {
    if [[ $(grep -i "$search1" people.dat | grep -i "$search2") ]]; then
        echo yes
    fi
}

@munircontractor is on the right track . You can do it even simpler:

function and {
    if grep -i "$search1" people.dat | grep -qi "$search2"; then
        echo yes
    fi
}

The output of the first grep will be empty if nothing matches, the exit code will be ignored, and the output will be sent through the pipe. The second grep will stop searching as soon as it finds a match, will not print anything, and whether it finds something or not will determine the exit code of the whole pipeline.

Other tips:

  • You can use simply while true
  • You probably want to use read -r to avoid treating backslashes as escaping special characters

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