Reputation: 31481
I need to update a website that is moving to a new host. I would like to add the following line to each file, only once, after the first occurrence of <?php
:
define('FRAMEWORK_LOCATION', '/home/someUser/framework.php');
I have tried several variations of this Perl oneliner:
$ find . -name '*' -print0 | xargs -0 perl -pi -e 's|<?php|<?php\rdefine('\''FRAMEWORK_LOCATION'\'', '/home/someUser/framework.php');'
However, as can be seen it would affect all lines. I am not particularly concerned about the case of additional code after the initial <?php
though if a solution does take that into account then that would be good for me to learn from as well.
Upvotes: 0
Views: 124
Reputation: 4470
You can directly use sed, without invoking perl:
$ find . -name '*' -type f -print0 | xargs -0 sed -e '0,/<?php/s||&\ndefine("FRAMEWORK_LOCATION","/home/someUser/framework.php")|'
The relevant bit is:
sed -e '0,/<?php/s||&\nNEW_TEXT|'
where you are specifying:
0,/<?php
: from the first line to the first occurrence of <?php
s||&\nNEW_TEXT|
: where you substitute the previous match <?php
with itself followed by a new line with some new text.Note that I added the switch -type f
to find
for filtering out directories.
Upvotes: 1
Reputation: 25249
Try this one:
find . -name "*" -print0 | xargs -0 sed '0,/<?php/s/<?php/<?php\n\tdefine(...)/'
Upvotes: 1
Reputation: 1128
perl -ie 'undef $/; $txt = <>; $txt =~ s|<?php|<?php\rdefine("FRAMEWORK_LOCATION", "/home/someUser/framework.php")|; print $txt;'
or
perl -ie '$first = 1; while (<>) { if ($first && s|<?php|<?php\rdefine("FRAMEWORK_LOCATION", "/home/someUser/framework.php")|) { $first= 0; } print; }'
Upvotes: 2