Search code examples
pythonpowershellbatch-fileline-breaks

Changing two lines of code with powershell in a .bat


I've been following this post and I've used this code in the .bat:

powershell -Command "(gc -Raw test.py) -replace 'test = ''lol''`r`nlol = ''test''', 'test1 = ''lol1''`r`nlol2 = ''test2''' | Out-File test2.py"

It does recognise backtick r backtick n because if replaces this file: enter image description here

by this file: enter image description here

My problem is that in the created file, I have backtick r backtick n instead of linebreaks. Is it normal? Am I missing something?

I also tried using \r\n instead of backticks r backticks n and the same happens (it's recognised but in the output file there is \r\n and not an actual linebreak (I'm on Windows 11).


Solution

  • You need to use double-quotes for escape sequences, see about_Special_Characters.

    An example for you to test:

    $text = @'
    test = 'lol'
    lol = 'test'
    '@
    
    $text -replace "test = 'lol'\r?\nlol = 'test'", "test1 = 'lol1'`r`nlol2 = 'test2'"
    

    As for your call to powershell.exe from the batch file, I believe this could work (you can use "^"" for escaping):

    powershell -Command "(gc -Raw test.py) -replace "^""test = 'lol'\r?\nlol = 'test'""", """test1 = 'lol1'`r`nlol2 = 'test2'"^"" | Out-File test2.py"
    

    All credits on the call to cmd and the required escaping goes to this answer.