-1

I am very new to powershell. I have a csv file that i want to find and replace some text with. after some searching, this seems simple to do, but i still seem to be having problems with the code:

$csv = get-content .\test.csv
$csv = $csv -replace "|", "$"
$csv | out-file .\test.csv

My file is located here: C:\Users\CB1\test.csv How do I specify that location in powershell?

I've tried this but it doesn't work:

$csv = get-content C:\Users\CB1\test.csv
$csv = $csv -replace "|", "$"
$csv | out-file C:\Users\CB1\test.csv
Carlo B.
  • 119
  • 2
  • 16

1 Answers1

1

The problem isn't whether you're using relative or absolute paths (assuming your relative paths are relative to the right directory).

Rather, the problem is that the -replace operator is regex-based, and that | is therefore interpreted as a regex metacharacter (representing alternation).

Therefore, you need to escape such metacharacters, using \ (or, if you were to do this programmatically, you could use the [regex]::Escape() method).

Additionally, since your replacement operation isn't line-specific, you can speed up your operation by reading the file into memory as a whole, using the -Raw switch.

That, in turn, requires that you use the -NoNewLine switch when (re)writing the file. Also, with text input, Set-Content is preferable to Out-File for performance reasons.

To put it all together:

(Get-Content -Raw .\test.csv) -replace '\|', '$' | Set-Content -NoNewLine .\test.csv

Note: Use the -Encoding parameter as needed, as the input file's encoding will not be honored:

  • In Windows PowerShell, Out-File produces UTF-16LE ("Unicode") files by default, whereas Set-Content uses the system's ANSI code page.

  • In PowerShell (Core) 7+, BOM-less UTF-8 is the consistently applied default.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Thanks! that worked great. Is there a way to list multiple characters to replace? for example if i wanted to replace: '/|' and ' /'' and '/"' all with '$'? – Carlo B. May 05 '21 at 02:29
  • @CarloB., use a [character set](https://www.regular-expressions.info/charclass.html): `'[|''"]'` – mklement0 May 05 '21 at 04:34