Tool
Tool

Reputation: 12498

Shell and sed: adding an array element to a PHP file

I have a php file:

<?php
return array(
    'modules' => array(
        'Application',
        'DoctrineModule',
        'DoctrineORMModule'
    ),
);

Since I'm lazy, I'm writing a script that will add an element to 'modules' array with a simple call:

$ sh myscript.sh 'NewModule'

NewModule should be added after the last 'modules' element.

I tried doing this with 'sed' command but I didnt succeed yet. Any help is welcome.

Upvotes: 0

Views: 603

Answers (2)

ghoti
ghoti

Reputation: 46886

As I suggested in comments, I think an easier way would be to read the new data using file(), which turns things into an array already.

<?php

$thing=array(
    'modules' => array(
        'Application',
        'DoctrineModule',
        'DoctrineORMModule'
    )
);

foreach(file("modules.txt") as $new) {
  $thing['modules'][]=trim($new);
}

print_r($thing);

And the results:

[ghoti@pc ~]$ cat modules.txt
foo
bar
[ghoti@pc ~]$ echo "snerkle" >> modules.txt 
[ghoti@pc ~]$ php -f myphpfile.php 
Array
(
    [modules] => Array
        (
            [0] => Application
            [1] => DoctrineModule
            [2] => DoctrineORMModule
            [3] => foo
            [4] => bar
            [5] => snerkle
        )

)
[ghoti@pc ~]$ 

The only reason to use foreach(){} is to let you trim() each element. If you don't mind the elements of ['modules'] having newlines on the end, you can simply replace the loop with:

$thing['modules']=array_merge($thing['modules'], file("modules.txt"));

I'm not sure what your return was about. Perhaps the code in your question was an excerpt from a function. Anyway, this should be enough to get the idea across.

Upvotes: 1

Steve
Steve

Reputation: 54572

Here's one way using GNU sed:

sed '/modules..=>.array/,/),/ { /[^(,]$/ s//&,\n        '\''NewModule'\''/ }' file.php

Results:

<?php
 return array(
    'modules' => array(
        'Application',
        'DoctrineModule',
        'DoctrineORMModule',
        'NewModule'
    ),
);

You can make the regex more strict if you'd like. But I'll leave that job up to you.

Upvotes: 1

Related Questions