How to convert a file LF to CRLF

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

This topic contains 6 replies, has 5 voices, and was last updated by

js
 
Participant
1 month ago.

  • Author
    Posts
  • #177709

    Participant
    Topics: 4
    Replies: 6
    Points: 66
    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: 8
    Replies: 1213
    Points: 756
    Helping Hand
    Rank: Major Contributor

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

  • #177715

    Participant
    Topics: 9
    Replies: 425
    Points: 691
    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: 497
    Points: 1,230
    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: 25
    Replies: 692
    Points: 1,721
    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: 66
    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: 25
      Replies: 692
      Points: 1,721
      Helping Hand
      Rank: Community Hero

      No, but you can up arrow me on stackoverflow.

You must be logged in to reply to this topic.