grep "${array[*]}" Textfile
Will work as long as you set IFS
to newline (or anything that starts with newline), and use --
or -e
to make sure it still works even if the first element starts with -
.
"${array[*]}"
in Korn-like shells, like "$*"
in POSIX shells expands to the list of elements joined with the first character of $IFS
. The default value of $IFS
is <SPC><TAB><NL>
(<SPC><TAB><NL><NUL>
in zsh
), so by default, you'd get the element joined with SPC characters. For grep
, you'd need the different regexps to be newline separated for grep
to loop for each one in turn.
IFS=$'\n'
grep -e "${array[*]}" file
In zsh
, a cleaner approach would be grep -e "${(F)array}" file
(where the F
parameter expansion flag, short for pj[\n]
, explicitly j
oins with n
ewline (aka lineF
eed) instead of modifying $IFS
globally), or grep -e$^array file
(which expands the array in fish
/rc
-style, where that becomes grep -efirst -esecond file
which is another way to supply several patterns to grep
.
Another option is to do:
printf '%s\n' "${array[@]}" | grep -f - file
This time passing the newline-delimited list of patterns over grep
's stdin rather than via an argument.
Those approaches would work whether your patterns are fixed strings (with -F
), extended regexps (with -E
) or basic regexps (default).
You may want to make sure the list of patterns is not empty:
(( ${#array[@]} > 0 )) && grep ...
Calling grep
with an empty pattern yields different results depending on the grep
implementation and generally not what you want.
grep -f
?