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

   'key1' => array(
       'val1' => 'val',
       'val2' => 'val',
       'val3' => 'val',
   'key2' => array(
       'val1' => 'val',
       'val2' => 'val',
       'val3' => 'val',

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?


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

sed -n '/key1/,/)/p' file.txt

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 ).

  • Right answer, but useless use of cat – Dan Andreatta Apr 26 '10 at 20:31
  • Ah, indeed. I will fix this right away. – Karol J. 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 J. Piczak Apr 26 '10 at 20:55

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.

  • Nice, I did not know about this one. – Dan Andreatta Apr 27 '10 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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