Search code examples
powershellpowershell-5.0

Editing a text file inside PowerShell Script


I made a Powershell script to update my mpv scripts. One of them being this https://raw.githubusercontent.com/mpv-player/mpv/master/player/lua/osc.lua I want the script to edit and remove all instances of show_message(get_playlist(), 3) from the file.

I tried (get-content .\Scripts\osc.lua) | foreach-object {$_ -replace "show_message(get_playlist(), 3)", ""} | Out-File .\Scripts\osc.lua and (get-content .\portable_config\Scripts\osc.lua) | foreach-object {String.Replace [RegEx]::Escape('show_message(get_playlist(), 3)'),''} | Out-File .\portable_config\Scripts\osc.lua but they dont seem to work.

Basically I want the script to automatically download osc.lua(which works fine as intended) and then remove all instances of show_message(get_playlist(), 3) from the file. My PowerShell version is 5.1.


Solution

  • You can use the following with the Replace Operator:

    $regex = [regex]::Escape('show_message(get_playlist(), 3)')
    (Get-Content .\Scripts\osc.lua) -replace $regex |
        Set-Content .\Scripts\osc.lua
    

    Alternatively, you can use the String.Replace method from the String class, which does not use regex.

    (Get-Content .\Scripts\osc.lua).Replace('show_message(get_playlist(), 3)','') |
        Set-Content .\Scripts\osc.lua
    

    Explanation:

    When using the -replace operator, the matching mechanism is a regex match. Certain characters are metacharacters for regex and must be escaped before they can be interpreted literally. In this case ( and ) need to be escaped. You can either do that manually with \ (\( and \)) or use the Escape() method from the Regex class. From the code above, you can type $regex after its declaration and see how it was escaped.

    When replacing a string with an empty string, you do not need to specify a replacement string. 'String' -replace 'ing' has the same results as 'String' -replace 'ing',''


    Note: You are mixing Get-Content and Out-File in your code without using the -Encoding parameter. It is possible you could output a different encoding than the original file. If this matters to you, I'd suggest using the -Encoding parameter with the appropriate encoding.