Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do a grep with keywords stored in the array?

Tags:

grep

bash

shell

Is it possible to do a grep with keywords stored in the array.

Here is the possible code snippet; how can I 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 search for only one keyword. I would like to search for all the keywords which is stored in args array.

like image 649
Kiran Avatar asked Feb 19 '10 09:02

Kiran


People also ask

Can you grep an array?

You can use Grep to filter enumerable objects, like Arrays & Ranges.

How can an array store grep results?

You can use: targets=($(grep -HRl "pattern" .)) Note use of (...) for array creation in BASH. Also you can use grep -l to get only file names in grep 's output (as shown in my command).

How do I echo an array in bash?

How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.


1 Answers

You can use some bash expansion magic to prefix each element with -e and pass each element of the array as a separate pattern. This may avoid some precedence issues where your patterns may interact badly with the | operator:

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

The downside to this is that you cannot have any spaces in your patterns because that will split the arguments to grep. You cannot put quotes around the above expansion, otherwise you get "-e pattern" as a single argument to grep.

like image 110
camh Avatar answered Oct 09 '22 06:10

camh