Let's say I have a file with a long nested array, that's formatted like this:

array(
   'key1' => array(
       'val1' => 'val',
       'val2' => 'val',
       'val3' => 'val',
   ),
   'key2' => array(
       'val1' => 'val',
       'val2' => 'val',
       'val3' => 'val',
   ),
   //etc...
);

what I would like to do is have a way to grep/search a file, and by knowing key 1, get all the lines (the sub-array) it contains. is this possible?

link|improve this question

71% accept rate
feedback

3 Answers

up vote 2 down vote accepted

Not with grep but you should be able to do it with awk or sed:

sed -n '/key1/,/)/p' file.txt
link|improve this answer
feedback

If there are no more levels of nested arrays, then this should work:

awk '/key1/,/\)/' my_input_file

Basically, it prints from key1 to next closing bracket ).

link|improve this answer
Right answer, but useless use of cat – Dan Andreatta Apr 26 '10 at 20:31
Ah, indeed. I will fix this right away. – Karol Piczak Apr 26 '10 at 20:33
I tried what you said, awk throws a 'backslash not last character on line' error – GSto Apr 26 '10 at 20:34
I'm not sure. My knowledge of sed/awk is rudimentary. It works on mawk though - I tested. Maybe there's some difference in how it's handled. – Karol Piczak Apr 26 '10 at 20:55
feedback

If it is a fixed number of items in the array, you can use the -A (lines after switch) with grep:

grep -A4 'key1' myfile 

   -A NUM, --after-context=NUM
          Print NUM  lines  of  trailing  context  after  matching  lines.
          Places   a  line  containing  a  group  separator  (--)  between
          contiguous groups of matches.  With the  -o  or  --only-matching
          option, this has no effect and a warning is given.

There is also -B for before lines as well.

link|improve this answer
Nice, I did not know about this one. – Dan Andreatta Apr 27 '10 at 12:51
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.