Multi-line return from grep into an array?
I was playing with a bash script earlier, that cat'd a file and grep'd it for something like "A|B". This returned a multiple number of lines, so that the output from grep was
line A.1 line A.2 line B.1 line B.2 etc. which obviously contains a new line after each line. Right now I'm redirecting the result of the cat | grep to a file, and then cat | while read'ing that file in order to separately access each of the lines. There's *got* to be a way to do this without the external file..I just can't figure out how to somehow shoehorn the return of grep into a bash array or anything else iterate-able. To let you know what I've tried: - setting IFS to newline, but it seems that only cat pays attention to IFS...echo doesn't. And I can only cat a file, not a variable (that I've seen, anyway). - I also gave piping the result to awk 'BEGIN {FS=" "} ...but there I got stuck, both because bash complains about that syntax and missing ending quotes and all that, but also because I've only seen that when followed immediately by {print $1 $2 $3} ..and I have no way of knowing how many lines will be returned. Any pointers in the right direction would be appreciated! |
Hope I got this correct. You have the result of something and you want get it line by line in a variable.
Instead of redirecting it to file try piping it to a while read loop. First of all there's no need to Code:
cat <filename> |grep <pattern> Just Code:
grep <pattern> <filename> SO try something like Code:
grep <pattern> <filename> | while read a; do ...... ; done |
You should be able to use:
IFS=" " for $line in `grep STRING FILE`;do echo Line: $line done |
All times are GMT -5. The time now is 07:25 AM. |