Find string in file and append new string after

Hi All,

I'm trying to insert a string into a file at a specific location.

I'd like to add a string after the

parent::__construct();

in my file.

<?php  if (! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Controller extends CI_Controller {

	function __construct()
	{
		parent::__construct();
                NEW STRING
	}

I've tried to use the a combination of grep and sed but I don't seem to be having much luck. Any help would be appreciated.

---------- Post updated at 09:09 PM ---------- Previous update was at 09:03 PM ----------

Just a note. I have tried to following with no success

$(grep -q "parent::__construct();" application/core/MY_Controller.php)
if [ $? -eq 1 ]; then
    sed '/parent::__construct();/ a\ string2' application/core/MY_Controller.php
fi
sed -e 's/\(parent::__construct();\)/\1\nNEW STRING/'

The following multi-line should work with all sed versions

sed '
/parent::__construct();/ a\
string2
' application/core/MY_Controller.php

or

sed '
s/parent::__construct();/&\
string2/
' application/core/MY_Controller.php

Your grep-if is faulty somehow. Perhaps you want

grep -q "parent::__construct();" application/core/MY_Controller.php
if [ $? -eq 0 ]; then

Using awk and getting text at correct position (tabbed)

awk -F"\t" '/parent::__construct()/ {$0=$0"\n";for (i=1;i<NF;i++)t=t "\t";$0=$0 t "NEW STRING"}1' application/core/MY_Controller.php
<?php  if (! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Controller extends CI_Controller {

        function __construct()
        {
                parent::__construct();
                NEW STRING
        }
1 Like

Thanks @Jotne. I guess now all I have to do is make a temp file and move that back over the original. Also thanks to @MadeInGermany & @Smiling Dragon

sed 's/\(parent::__construct();\)/&<patern want to add>/g' <file>

This add text behind parent::__construct(); , not on a new line below as requested.