Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

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
share|improve this answer

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

share|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

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.

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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