Can grep be used with keywords stored in an array?

Is it possible to execute grep with keywords stored in an array.

Here is a possible piece of code ... Please correct it.

args=("key1" "key2" "key3") cat file_name |while read line echo $line | grep -q -w ${args[c]} done 

At the moment I can only find one keyword. I would like to find all the keywords that are stored in the args array.

Any suggestion would be highly appreciated.

Thank you Kieran

+6
bash shell grep
source share
5 answers
 args=("key1" "key2" "key3") pat=$(echo ${args[@]}|tr " " "|") grep -Eow "$pat" file 

Or with a shell

 args=("key1" "key2" "key3") while read -r line do for i in ${args[@]} do case "$line" in *"$i"*) echo "found: $line";; esac done done <"file" 
+5
source share

This is one way:

 args=("key1" "key2" "key3") keys=${args[@]/%/\\|} # result: key1\| key2\| key3\| keys=${keys// } # result: key1\|key2\|key3\| grep "${keys}" file_name 

Edit:

Based on the proposal of Pavel Shved :

 ( IFS="|"; keys="${args[*]}"; keys="${keys//|/\\|}"; grep "${keys}" file_name ) 

First version as single line:

 keys=${args[@]/%/\\|}; keys=${keys// }; grep "${keys}" file_name 

Edit2:

Even better than the version using IFS :

 printf -v keys "%s\\|" "${args[@]}"; grep "${keys}" file_name 
+3
source share

You can use the bash extension magic to prefix each element with -e and pass each element of the array as a separate template. This can avoid some priority issues where your templates may not interact well with | Operator:

 $ grep ${args[@]/#/-e } file_name 

The disadvantage of this is that you cannot have spaces in the templates, because it will split the arguments into grep. You cannot put quotation marks around the above extension, otherwise you will get a "-e pattern" as the only grep argument.

+2
source share

Team

 ( IFS="|" ; grep --perl-regexp "${args[*]}" ) <file_name 

Searches for a file for each keyword in the array. He does this by creating a regular expression word1|word2|word3 that matches any word from the above alternatives (in perl mode).

If I have a way to combine the elements of an array into a string, dividing them into a sequence of characters (namely \| ), this can be done without perl regexp.

+1
source share

perhaps something like this;

 cat file_name |while read line for arg in ${args[@]} do echo $line | grep -q -w $arg} done done 

not tested!

0
source share

All Articles