Monday, February 26, 2024
 Popular · Latest · Hot · Upcoming
rated 0 times [  2] [ 0]  / answers: 1 / hits: 689  / 1 Year ago, sun, september 18, 2022, 6:38:52

I have a sequence of search patterns stored in a bash array (ptrn), which I want to pass to a grep command. How can I do it?

  ptrn=("FN" "DS")
for fl in "$@"; do # loop through number of files
if [[ -f "$fl" ]]; then
printf '

' "$mgn" "==> $flnm <==" "$rst"
grep --color "$ptrn" "$flnm"

More From » bash


Two options:

  • Standards-compliant way: Join the patterns with newline and provide it as single argument:

    grep -e "$(printf "%s
    " "${ptrn[@]}")" ...

    (This feature is specified by the POSIX standard: "The pattern_list's
    value shall consist of one or more patterns separated by <newline> characters ...")

  • Non-standard, but still safe way: When using a shell with arrays, like, e.g., bash, build an array of arguments to grep:

    for p in "${ptrn[@]}"
    args+=(-e "$p")
    grep "${args[@]}" ...

    This is safe from field-splitting and globbing, and in general is how command lines should be built from variables.

[#10] Monday, September 19, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 347
Total Questions: 112
Total Answers: 108

Location: Ukraine
Member since Wed, Dec 16, 2020
3 Years ago