Search and Replace CRLF

Tagged: , ,

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 3 years, 2 months ago.

  • Author
    Posts
  • #14302
    Profile photo of patrick metcalfe
    patrick metcalfe
    Participant

    Trying to replace CRLF in a small PowerShell script

    Works OK with standard characters bit not with `n ;

    file.txt look like this:

    Line1
    Line2
    Line3
    Line4

    would like the file to look like this:

    Line1,Line2,Line3,Line4

    Here is the script below

    $Strings = Get-Content e:\powershell\file.txt

    Foreach ($String in $Strings){

    $string -replace ("`n" , ",")
    }

  • #14303
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Get-Content returns an array of strings, by default, and those strings will not include the actual CR/LF characters that were present in the file. All you need to do is use the -join operator to combine the array back into a single comma-separated string:

    $String = (Get-Content e:\powershell\file.txt) -join ','
    

You must be logged in to reply to this topic.