DaveFar
DaveFar

Reputation: 7467

Storing multiple grep parameters in a bash variable

I want to store multiple grep parameters in a bash variable, so I can define the parameters in the configuration section at the top of my file, and use it in multiple locations.

How do I need to define the variable and write the grep command?

Details

My first attempt

# CONFIG: grep parameters to further filter ...                                                                  
GREP_PARAM="-E .*"

# ...

grep "^Stop " $1 | grep $GREP_PARAM | sed "..." >>$TFILE

results in

grep: ..: Is a directory

Using .\* or .\\* instead causes grep to not match anything, instead of everything.

Using grep "$GREP_PARAM" instead only works if GREP_PARAM contains a single parameter, but not otherwise; e.g. if it contains -v .*SAT.* or -v .\*SAT.\* or -v .\\*SAT.\\*, I get

grep: invalid option --

Upvotes: 1

Views: 154

Answers (1)

chepner
chepner

Reputation: 532418

This is exactly what arrays were introduced to handle.

grep_options=(-E '.*')

grep "^Stop " "$1" | grep "${grep_options[@]}" | sed "..." >> "$TFILE"

Upvotes: 4

Related Questions