Replace CRLF does not work, when using "get-content"

Welcome Forums General PowerShell Q&A Replace CRLF does not work, when using "get-content"

This topic contains 3 replies, has 2 voices, and was last updated by

 
Participant
3 months, 3 weeks ago.

  • Author
    Posts
  • #105161

    Participant
    Points: 0
    Rank: Member

    Hey guys,

    I'm super new to powershell.

    What I want to achieve is this:
    Before:
    select *
    from 'table'
    After:
    select * from 'table'

    If I write this statement directly into the Code for example:

    $SQL_output =" select *
    from 'table'"
    $SQL_outputneu = ($SQL_output -replace " select \*`n", " select *")
    $SQL_outputneu

    Then it works correctly and it replaces the new line.

    But
    If I load a file with the exact same statement into $SQL_output it does not work.
    For example this code:
    $q_path="H:\xxx.txt"
    $SQL_output = (Get-content $q_path)
    $SQL_outputneu = ($SQL_output -replace " select \*`n", " select *")
    $SQL_outputneu

    Anyone can help?
    Thank you 🙂

  • #105167

    Participant
    Points: 165
    Helping Hand
    Rank: Participant

    Get-Content splits lines on line feeds as is and creates an array of strings, one line per item. In order to disable the splitting to get the behaviour you want, you will need to add the -Raw parameter. 🙂

    • #105175

      Participant
      Points: 0
      Rank: Member

      Thanks for the help, works now!

      At first it still didn't work, but I just noticed that I had to add "`r" to the RegExpr. 😀

    • #105184

      Participant
      Points: 165
      Helping Hand
      Rank: Participant

      Ah, yeah, that'd probably do it. I shoulda noticed that!
      CR = 'cursor return(?)' = `r
      LF = 'line feed' = `n

      This can vary depending on OS and what some editors will use, though, so be careful!

      If you need to split on any of multiple types of newline sequences, you can do a regex split using the various kinds:

      $String -split "`r`n|`n|`n`r"

      (pipe in regex is an 'or')

The topic ‘Replace CRLF does not work, when using "get-content"’ is closed to new replies.