'Grep multiple bash parameters

I'm writing a bash script which shall search in multiple files.

The problem I'm encountering is that I can't egrep an undetermined number of variables passed as parameters to the bash script

I want it to do the following:

Given a random number of parameters. i.e:

./searchline.sh A B C

Do a grep on the first one, and egrep the result with the rest:

grep "A" * | egrep B | egrep C

What I've tried to do is to build a string with the egreps:

for j in "${@:2}";
do
ADDITIONALSEARCH="$ADDITIONALSEARCH | egrep $j";
done

grep "$1" * "$ADDITIONALSEARCH"

But somehow that won't work, it seems like bash is not treating the "egrep" string as an egrep.

Do you guys have any advice?

By the way, as a side note, I'm not able to create any auxiliary file so grep -f is out of the line I guess. Also note, that the number of parameters passed to the bash script is variable, so I can't do egrep "$2" | egrep "$3".

Thanks in advance.

Fernando



Solution 1:[1]

You can use recursion here to get required number of pipes:

#!/bin/bash

rec_egrep() {
    if [ $# -eq 0 ]; then
        exec cat
    elif [ $# -eq 1 ]; then
        exec egrep "$1"
    else
        local pat=$1
        shift
        egrep "$pat" | rec_egrep "$@"
    fi
}

first_arg="$1"
shift
grep "$first_arg" * | rec_egrep "$@"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yorik.sar