1

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?

3 Answers 3

2

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

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

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

4
  • Right answer, but useless use of cat Commented Apr 26, 2010 at 20:31
  • Ah, indeed. I will fix this right away. Commented Apr 26, 2010 at 20:33
  • I tried what you said, awk throws a 'backslash not last character on line' error Commented Apr 26, 2010 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. Commented Apr 26, 2010 at 20:55
0

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.

1
  • Nice, I did not know about this one. Commented Apr 27, 2010 at 12:51

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.