0

I am passing input to grep from previously declared variable that contains multiple lines. My goal is to extract only certain lines. As I increase the argument count in grep, the readability goes down.

var1="
_id=1234
_type=document
date_found=988657890
whateverelse=1211121212"


echo "$var1"

_id=1234
_type=document
date_found=988657890
whateverelse=1211121212


grep -e 'file1\|^_id=\|_type\|date_found\|whateverelse' <<< $var1
_id=1234
_type=document
date_found=988657890
whateverelse=1211121212

My idea was to pass parameters from array and it will increase readibility:

declare -a grep_array=(
"^_id=\|"
"_type\|"
"date_found\|"
"whateverelse"
)

echo ${grep_array[@]}
^_id=\| _type\| date_found\| whateverelse


grep -e '${grep_array[@]}' <<<$var1

---- no results

How can I do it with grep to pass parameters with multiple OR conditions from somewhere else not one line? As I have more arguments the readibility and manageability goes down.

1
  • if the lines are cotngiuous and are using GNU grep, look at Context control in grep --help to get n lines context, maybe more suitable Commented Mar 22, 2019 at 12:09

1 Answer 1

1

Your idea is right but you've got couple of issues in the logic. The array expansion of type ${array[@]} puts the contents of the array as separate words, split by the white space character. While you wanted to pass a single regexp string to grep, the shell has expanded the array into its constituents and tries it to evaluate as

grep -e '^_id=\|' '_type\|' 'date_found\|' whateverelse

which means each of your regexp strings are now evaluated as a file content instead of a regexp string.

So to let grep treat your whole array content as a single string use the ${array[*]} expansion. Since this particular type of expansion uses the IFS character for joining the array content, you get a default space (default IFS value) between the words if it is not reset. The syntax below resets the IFS value in a sub-shell and prints out the expanded array content

grep -e "$(IFS=; printf '%s' "${grep_array[*]}")" <<<"$str1"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.