Skip to content
Advertisement

Function to search of multiple patterns using grep

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.

Advertisement

Answer

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 "$@"
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement