Author Posts

July 25, 2018 at 10:26 am

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 🙂

July 25, 2018 at 12:28 pm

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. 🙂

July 25, 2018 at 12:56 pm

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. 😀

July 25, 2018 at 1:22 pm

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')