user2664313
user2664313

Reputation: 13

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

Upvotes: 1

Views: 2451

Answers (2)

konsolebox
konsolebox

Reputation: 75608

A safe eval can be a good solution:

#!/bin/bash

if [[ $# -gt 0 ]]; then
    temp=(egrep -e "\"\$1\"" '*')

    for (( i = 2; i <= $#; ++i )); do
        temp+=('|' egrep -e "\"\${$i}\"")
    done

    eval "${temp[@]}"
fi

To run it:

bash script.sh A B C

Upvotes: 3

Yorik.sar
Yorik.sar

Reputation: 5947

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 "$@"

Upvotes: 4

Related Questions