If your patterns/words stored as array elements are guaranteed to not have spaces or non-escaped shell special characters in them, then you can use bash
's parameter expansion to pass the array elements to grep
as separate individual patterns e.g. -e FN -e DS ...
like so:
ptrn=("FN" "DS")
# Prepend "-e" to each array element
ptrn2="${ptrn[@]/#/-e }"
# Don't quote "$ptrn2" or it will be passed as a single token and wouldn't work.
grep --color $ptrn2 file
Or if they might contain non-escaped shell special characters, you can build the regular expressions around |
(or) (splitting on all spaces as well but not failing) and use it with something like:
ptrn=("FN" "DS")
# Translate spaces " " single or multiple including spaces between words in a single array element into "|".
ptrn2="$(echo ${ptrn[@]} | tr " " "|")"
# -E enables extended regular expressions ... needed for this to work.
grep --color -E "$ptrn2" file
Or to preserve exact spaces inside each regular expression pattern passing each array element as an individual token and building an extended regular expression of them using the |
(logical or), you can do something like this:
ptrn=("FN" "DS")
# Append "|" to each array element.
ptrn2="$(printf '%s|' "${ptrn[@]}")"
# Delete the last character i.e. the extra "|".
ptrn2="${ptrn2::-1}"
# -E enables extended regular expressions ... needed for this to work.
grep --color -E "$ptrn2" file