3

I want to modify every file in a directory recursively.

I want to replace:

<?php

with

 <?php
 /**
  *
  * Copyright (C) MyCompany, Ltd. - All Rights Reserved
  * Unauthorized copying of this file, via any medium is strictly prohibited
  * Proprietary and Confidential
  * Written by Justin E <justin@domain.tld>, March 2014
  *
  */

What would be the best solution? I know some sed, but I am looking to keep the spacing and newlines as well so that it looks professional.

Justin E
  • 133
  • http://stackoverflow.com/a/151684 – Justin E Mar 25 '14 at 23:43
  • I've never flagged my own question before... – Justin E Mar 25 '14 at 23:48
  • Possible dupe of http://unix.stackexchange.com/q/110815/4671 – Faheem Mitha Apr 18 '14 at 17:59
  • @FaheemMitha This is not a dupe, the link you mentioned discusses applying changes to a list of files, I just wanted to be able to send my script an extension, and it apply to all files that match that extension. Could you imagine having roughly 2000 php files to apply this too? What kind of script would you be looking at if you listed every file. What if you did not know the names of every file? – Justin E Apr 18 '14 at 18:20
  • Also, as you can see above, I already flagged my own question as a duplicate of a question on stackoverflow. – Justin E Apr 18 '14 at 18:23

1 Answers1

4

I would create a file as dummy with the contents that you want to be replaced. So dummy file would look like below.

<?php
 /**
  *
  * Copyright (C) MyCompany, Ltd. - All Rights Reserved
  * Unauthorized copying of this file, via any medium is strictly prohibited
  * Proprietary and Confidential
  * Written by Justin E <justin@domain.tld>, March 2014
  *
  */

After that, I would execute the below script.

for f in ./*; do
sed -i '/<?php/{
    s/<?php//g
    r dummy
}' $f
done

I am replacing the <?php with spaces and replacing it with the contents from the dummy file.

Ramesh
  • 39,297
  • 1
    Are you going to replace all <?php or just the beginning of the file alone? If just the beginning of the file, the above script needs to be changed a bit. :) – Ramesh Mar 25 '14 at 23:56
  • It will be just the beginning of the file. – Justin E Mar 25 '14 at 23:59
  • You can take a look into the manual here. http://www.linuxtopia.org/online_books/linux_tool_guides/the_sed_faq/sedfaq4_004.html to just replace the first occurence. – Ramesh Mar 26 '14 at 00:16