How can I replace newlines using PowerShell?

前端 未结 5 2051
野的像风
野的像风 2020-12-08 18:24

Given test.txt containing:

test
message

I want to end up with:

testing
a message

I think the fol

相关标签:
5条回答
  • 2020-12-08 19:03

    A CRLF is two characters, of course, the CR and the LF. However, `n consists of both. For example:

    PS C:\> $x = "Hello
    >> World"
    
    PS C:\> $x
    Hello
    World
    PS C:\> $x.contains("`n")
    True
    PS C:\> $x.contains("`r")
    False
    PS C:\> $x.replace("o`nW","o There`nThe W")
    Hello There
    The World
    PS C:\>
    

    I think you're running into problems with the `r. I was able to remove the `r from your example, use only `n, and it worked. Of course, I don't know exactly how you generated the original string so I don't know what's in there.

    0 讨论(0)
  • 2020-12-08 19:08

    If you want to remove all new line characters and replace them with some character (say comma) then you can use the following.

    (Get-Content test.txt) -join ","
    

    This works because Get-Content returns array of lines. You can see it as tokenize function available in many languages.

    0 讨论(0)
  • 2020-12-08 19:08

    You can use "\\r\\n" also for the new line in powershell. I have used this in servicenow tool.

    In my case "\r\n" s not working so i tried "\\r\\n" as "\" this symbol work as escape character in powershell.

    0 讨论(0)
  • 2020-12-08 19:22

    In my understanding, Get-Content eliminates ALL newlines/carriage returns when it rolls your text file through the pipeline. To do multiline regexes, you have to re-combine your string array into one giant string. I do something like:

    $text = [string]::Join("`n", (Get-Content test.txt))
    [regex]::Replace($text, "t`n", "ting`na ", "Singleline")
    

    Clarification: small files only folks! Please don't try this on your 40 GB log file :)

    0 讨论(0)
  • 2020-12-08 19:26

    With -Raw you should get what you expect

    0 讨论(0)
提交回复
热议问题