Function to search of multiple patterns using grep

2019-06-14 19:57发布

问题:

I want to make a bash script to use grep to search for lines which have multiple patterns (case-insensitive). I want to create a bash script which I can use as follows:

myscript file.txt pattern1 pattern2 pattern3

and it should get traslated to:

grep -i --color=always pattern1 file.txt | grep -i pattern2 | grep -i pattern3

I tried following bash script, but it is not working:

#!/bin/bash
grep -i --color=always $2 $1 | grep -i $3 | grep -i $4 | grep -i $5 | grep -i $6 | grep -i $7 

The error is:

Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.

回答1:

I think you can do a recursive function:

search() {
    if [ $# -gt 0 ]; then
        local pat=$1
        shift
        grep "$pat" | search "$@"
    else
         cat
    fi
}

In your script you would call this function and pass the search patterns as arguments. Say that $1 is the file and the rest of the arguments are patterns then you would do

file=$1
shift
cat "$file" | search "$@"


回答2:

When you have GNU awk, you can use

awk 'BEGIN {IGNORECASE=1} /pattern1/ && /pattern2/ && /pattern3/' file.txt

EDIT: You can use this in a script like this:

inputfile="$1"
shift
awk -f <(echo "BEGIN {IGNORECASE=1}"; printf " /%s/ &&" $* | sed 's/&&$//') "${inputfile}"


回答3:

If you omit one argument or other at the end, so that $3 etc. will be missing, then some grep command will not receive an argument and will whine.



标签: linux bash shell