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?

GSto
  • 391
  • 1
  • 3
  • 8

3 Answers3

2

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

sed -n '/key1/,/)/p' file.txt
Dan Andreatta
  • 5,454
  • 2
  • 24
  • 14
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 ).

Karol J. Piczak
  • 2,358
  • 1
  • 20
  • 22
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.

Kyle Brandt
  • 83,619
  • 74
  • 305
  • 448