-2

I have a text file and I want to remove the last line break inside this file:
Text


with the following regex in Powershell:

(Get-Content .\test.txt -Raw) -replace ('\r\n(?=$)', '') | Set-Content .\test.txt

but this is not working.

I have the tried the regex-pattern: \r\n(?=$) to be replaced by '' in Notepad++ and Java and there it's working.

How can I get this to be working in Powershell?

Robin
  • 3
  • 2
  • Why don't you just [`string.Trim()`](https://learn.microsoft.com/en-us/dotnet/api/system.string.trim?view=netcore-3.1) it? – Robert Harvey Sep 01 '20 at 15:42
  • `Get-Content` already splits on `\r?\n`, so the output on which you're operating won't actually contain the line breaks. Sounds like you want `...|Set-Content -NoNewline` though – Mathias R. Jessen Sep 01 '20 at 15:45
  • @MathiasR.Jessen the `-NoNewline` switch did exactly what I wanted. – Robin Sep 01 '20 at 16:05
  • @MathiasR.Jessen but I don't understand your first point, because when I just try to replace all line breaks with `('\r\n', '')` it does the job except for the last line break. So I thought that the `-Raw` switch does ignore the line breaks by putting it into a string, but preserves it and makes it accessible for regex. So in the end the question why the `('\r\n(?=$)` does not work is still there for me. Can you explain this, please? – Robin Sep 01 '20 at 17:03
  • The `-replace` works fine removing the line break, but `Set-Content` appends a trailing line ending sequence back. – Wiktor Stribiżew Sep 01 '20 at 17:12
  • @WiktorStribiżew that answered the question! – Robin Sep 01 '20 at 17:21

1 Answers1

-2

You need to EOL Conversion to appropriate format. Linux and Dos have different end of line parameters and JSONs use Linux'.