Consider a command which takes arguments like this: cmd foo bar baz [arbitrary args...]. How do you build a filter of AND patterns based on those arguments?
Something like this pipeline of greps:
grep foo | grep bar | grep baz
I have a hunch I can avoid eval and also building a dynamic pipeline (out of a vague worry about Bash word expansion).
I tried reaching for AWK like this:
awk "$(printf '/%s/ && ' "$@" | awk '{ $NF=""; print }')"
- printf builds up the pattern based on args.
- Inner awk trims off some of the trailing
&&. - Outer awk runs the ANDs.
- Aside: On the edge case of 0 args, my script accidentally does the right thing—match everything—by running
awk '// '.
But I feel like my approach is clunky.
Edit: Ah! I just thought of another way which only uses two AWKs and is more explicit about the edge cases:
awk "$(echo "$@" | awk '
NF == 0 { print "//" }
NF > 0 { for (i = 1; i <= NF; i++)
printf("/%s/%s", $i, i==NF ? "" : " && ") }')"