1

From a SQL query (Postgres DB) the following line output is captured in a string:

    id         |                           title                            |     cur_status_time  

I am trying to replace the pipe character into something else.

 $line -replace "|",";"

but this is not working.

I tried:

$line.replace("|",";")

but its not working, either.

MMAX
  • 589
  • 1
  • 5
  • 9

1 Answers1

2

The -replace operator uses regex matching. The | is a special character in regex. You need to escape it with a backslash \:

$line = $line -replace "\|", ";"

Although this should have worked too:

$line = $line.Replace("|", ";")

Note: Strings in .NET are immutable (why?). Operations like Replace don't change the original string, so you have to assign the result back to $line.

marsze
  • 15,079
  • 5
  • 45
  • 61
  • Good point, I should have made that clearer. Since I was writing this up for own notes just now, let me offer an improved version. – mklement0 Oct 28 '20 at 17:56
  • It is advisable to use single quotes (`'...'`) with `-replace`, because `"..."` could create confusion with PowerShell's up-front string expansion (interpolation); e.g., `"$1"` would be interpreted as a variable reference. – mklement0 Oct 28 '20 at 17:56
  • If you do use `"..."` because you want to embed PowerShell variable values and expressions in the strings up front, be sure to escape `$` instances that are meant for the _regex engine_ as `\`$`. The alternative is to stick with single quotes and use the `-f` operator to embed a value; e.g. `'foo-{0}' -f $var`. Either way, a pitfall is that any metacharacters embedded in variable values will have syntactic meaning, and to treat them *verbatim* requires a call to `[regex]::Escape()` for the regex operand, and doubling of any embedded `$` characters for the substitution operand. – mklement0 Oct 28 '20 at 17:56