1

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

1
  • @fedorqui: '|' means OR, not and. When you pipe egrep, you want the intersection of the patterns, so an AND. Commented Aug 8, 2013 at 12:20

2 Answers 2

4

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 "$@"
Sign up to request clarification or add additional context in comments.

Comments

3

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

3 Comments

Wow, a use of eval that (at least as far as I can see) actually is safe! +1 for you, sir.
What's the value of defining temp as an array when eval is just going to concatenate it back into a single string before running that string through the parser?
@CharlesDuffy Preference. Also I think it's more efficient when the list of elements grows. A list is better that a repeatedly concatenated string. Also I might just use normal variables sometimes. Either method is fine. It's just up to you which you think is more convenient to write, although this time I think the use of an array is better.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.