Using grep search with array containing strings and spaces
Hi Everyone,
I want to be able to create an array that contains both strings and spaces within each element and use it as the pattern that grep will search for within a file. I know that I can do it if I explicitly type the string within the grep command. grep -ciw 'Hello world' file.txt But it doesn't seem to work when I place the string with spaces in an array. array[1]="'Hello'" array[2]="'Hello world'" grep -ciw "${array[1]} file.txt grep -ciw "${array[2]} file.txt grep for array[1] works, but the value for array[2] does not. I tried all the possible premutation with regular expression to get it to work, with no luck. Ultimately, I want to know if you can place single qoutes and or regular expressions within an array and have grep use it as a regular expression and not a literal value. Any help would be appreciated...Thanks!!! |
Hi,
try without the single-quotes: array[2]="Hello world" Invoke it with double-quotes: grep -ciw "${array[2]}" file.txt |
In scripting it's vital to understand how the shell handles arguments and whitespace. Read these three pages carefully:
http://mywiki.wooledge.org/Arguments http://mywiki.wooledge.org/WordSplitting http://mywiki.wooledge.org/Quotes Short form: double-quoting variables protects the contents from being word-split during expansion. |
Problem solved. Thanks for the help! THe wiki site on double quotes were extremely helpful!
|
All times are GMT -5. The time now is 09:35 AM. |