Let's say ptrn=(" a b" " 333 22 1 ")
.
Answer 1:
mptrn=$( printf -- ' -e %s' "${ptrn[@]}" )
grep -E "$mptrn" -- "$flnm"
The entire output of the command will be assigned to mptrn
, and the used format won't allow distinguishing between elements in the array if they contain space characters. mptrn
will contain -e a b -e 333 22 1
(with both a leading and trailing space character). When executing grep
, the quoted argument will be interpreted as a pattern argument because of the leading space, which will search for occurrences of "$mptrn"
in the given files, which is not what you're trying to achieve. To make a similar approach work you can use the IFS
parameter.
[ "${IFS+x}" = x ] && OLD_IFS=$IFS
IFS=$(printf '\x7f')
mptrn=$(printf "-e${IFS}%s${IFS}" "${ptrn[@]}")
# note that we don't use quotes
grep -E $mptrn -- "$flnm"
if [ "${OLD_IFS+x}" = x ]; then IFS=$OLD_IFS; else unset IFS; fi
Answer 2:
for i in "${!ptrn[@]}"; do
ptrn[$i]="-e ${ptrn[$i]}"
done
grep -E "${ptrn[@]}" -- "$flnm"
This answer is close to the desired result, except that the searched patterns will include a leading space, which means the resulting command looks like this:
grep -E "-e a b" "-e 333 22 1 " -- file
This can be solved by simply removing the space: ptrn[$i]=-e${ptrn[$i]}
.
Answer 3:
eptrn=()
for i in "${!ptrn[@]}"; do
eptrn+=("-e" "${ptrn[$i]}")
done
grep -E "${eptrn[@]}" -- "$flnm"
This answer is correct, the resulting grep
command will be:
grep -E -e " a b" -e " 333 22 1 " -- file