1

i have three variables $a, $b, $c. I don't know whether the three variables are set. I want the variable in the GREP query only if the variables are set. How do i do this?

find . -iname "*.txt" -type f | xargs grep -inw "$a" -sl | xargs grep -inw "$b" -sl |  xargs grep -inw "$c" -sl
find .* -iname "*.txt" -type f | xargs grep -iw "$a|$b|$c" -sl
3
  • 1
    Please edit your question to describe your overall goal. Perhaps you're going about it all wrong. Commented Jun 4, 2014 at 16:51
  • 1
    Your current edit makes even less sense than the original. Commented Jun 4, 2014 at 16:55
  • the second line is a query that i need to use in my script somewhere else. Commented Jun 4, 2014 at 17:00

1 Answer 1

1

You can prepare multiple -e arguments on an array:

args=()
for x in "$a" "$b" "$c"; do
    [[ -n $x ]] && args+=(-e "$x")
done
[[ ${#args[@]} -gt 0 ]] && find . -iname "*.txt" -type f | xargs grep -iw "${args[@]}" -sl

Note: Having -e "$a" -e "$b" -e "$c" is practically synonymous to "($a|$b|$c)" and might be even safer. Also if you don't intend "$a", "$b", and "$c" to be parsed as regex, you can just use fgrep or add the option -F; that which can't be done with "($a|$b|$c)".

Sign up to request clarification or add additional context in comments.

2 Comments

-n makes no sense in conjunction with -l.
Nope. You copied it exactly as he had it, even splitting the options into two groups for no reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.