Search code examples
regextext-filesnotepad

Regex: How to insert text before the first line and after the last line of file


I needed to add a php script on the beginning of 2000 files. So, I find the solution, maybe this will help anyone to do this with regex.


Solution

  • First, you have to select the first line on text: ^\A(.*)$

    Then, search and replace like this:

    Search: ^\A(.*)$

    Replace By: ANY_TEXT \r$1

    I use GrepWin to replace a big text, not just a single line. Remember that \r or \n are use to add a new line. If you don't want to use one of those, you will be able to add anything at the beginning of first line, without space it by another line ANY_TEXT $1

    Another way to to this:

    Search: \A(?-s){1}(?s)(.*)

    Replace By: ANY_TEXT \r$1

    And another way:

    Search: (?s)(.*)

    Replace by: ANYTHING \n\1

    Now, if you want to add something at the end of first line:

    Search: ^\A(.*)\K$

    Replace with: ANY_WORDS

    And, finally, if you want to add something after the last line on text:

    Search: ^(.*)$\z

    Replace by: $1 \nANY_WORDS