0

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.

1
  • 1
    It seems like you're expending extra effort to implement something that's more likely to break. If you're lazy, wouldn't it be less work to have your shell script simply write an extra line to a text file, then slurp that text file into the array using file()? Commented Oct 30, 2012 at 15:30

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.