Search code examples
newlinepowershell-5.0regexp-replace

powershell 5.1 - overwrite a file myText.txt by replacing every regex match with a newline character


Using powershell 5.1, why is my attempt to insert a newline at every regex match of myText.txt not working as i expect?

To my knowledge My regex works fine, it matches every 5th comma.

enter image description here

Unfortunately The code fails to inject/replace/insert a newline at every regex match. For some reason instead it adds a newline to the end every time i run the following statement:

To test this,

  1. Given a file, myText.txt that trails with a , and looks exactly like this: ,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,

  2. Run the command below and observe the results

$splitEveryNthComma = ((Get-Content -path .\myText.txt -Raw) -replace "(?<=^((,[^,]*){5})+),]","`n,") | Set-Content -Path .\myText.txt

How can i change my code above to get the "expected result" below?

Expected result of myText.txt:

,1,2,3,4,5
,6,7,8,9,10
,11,12,13,14,15
,16,17,

Actual result of myText.txt:

,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
{new line is added to the end. This is the bug im asking about.}

Solution

  • Your regex can be simplified

    ",1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17," -replace "((,[^,]*){5})", "`$1`n"
    

    gives

    ,1,2,3,4,5
    ,6,7,8,9,10
    ,11,12,13,14,15
    ,16,17,
    

    The regex (,[^,]*){5} captures the first / next 5 commas (including anything after them) and appends a newline after it. The parentheses in the expression groups it for the {5} (the outer parentheses in the code block above is what does the capture)