How to convert a file LF to CRLF

Welcome Forums General PowerShell Q&A How to convert a file LF to CRLF

  • This topic has 6 replies, 5 voices, and was last updated 4 months ago by
    js
    Participant
    .
Viewing 5 reply threads
  • Author
    Posts
    • #177709
      Participant
      Topics: 4
      Replies: 6
      Points: 67
      Rank: Member

      Is there a PowerShell command (or anything else) to convert the line endings within a text file from Unix-style (line-feed only) to Windows-style (carriage-return and line-feed), in place, without changing anything else (apart from modification date, which would be OK)?  In some *nix systems, there is a command called unix2dos.

    • #177712
      Participant
      Topics: 10
      Replies: 1375
      Points: 1,481
      Helping Hand
      Rank: Community Hero

      Have you attempted to search the interwebs? Using "powershell convert lf to crlf" there were many results

    • #177715
      Participant
      Topics: 9
      Replies: 427
      Points: 711
      Helping Hand
      Rank: Major Contributor

      Have you attempted to search the interwebs? Using "powershell convert lf to crlf" there were many results

      lol

    • #177891
      Participant
      Topics: 2
      Replies: 511
      Points: 1,307
      Helping Hand
      Rank: Community Hero

      Yeah, sure.

      $FilePath = "C:\Test\File.txt"
      (Get-Content -Raw -Path $FilePath) -replace '\n','\r\n' | Set-Content -Path $FilePath

       

    • #177918
      js
      Participant
      Topics: 27
      Replies: 736
      Points: 1,998
      Helping Hand
      Rank: Community Hero

      Yeah, sure.

      1
      2
      $FilePath = "C:\Test\File.txt"
      (Get-Content Raw Path $FilePath) -replace '\n','\r\n' | Set-Content Path $FilePath
      XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

      You can't use regex in the 2nd replace argument, plus set-content adds an extra newline unless you turn it off.

      # unix2dos
      (Get-Content -Raw -Path $FilePath) -replace '\n',"`r`n" | Set-Content -Path $FilePath -NoNewline
      

      I also posted a similar thing here with an extra regex negative lookbehind. https://stackoverflow.com/a/52593215/6654942

      What happened to quoting in the forum?

    • #178140
      Participant
      Topics: 4
      Replies: 6
      Points: 67
      Rank: Member

      Thank you, Joel and js!  That works.  I'm new to this forum — is there a way to credit you with helpful posts or problem solutions?

      • #178143
        js
        Participant
        Topics: 27
        Replies: 736
        Points: 1,998
        Helping Hand
        Rank: Community Hero

        No, but you can up arrow me on stackoverflow.

Viewing 5 reply threads
  • The topic ‘How to convert a file LF to CRLF’ is closed to new replies.