Ninja Cowgirl
Ninja Cowgirl

Reputation: 11281

replace a string in a csv file with powershell

I need to place System.Object[] for some columns in a csv file. I tried 3 different method but none of them are working. System.Object[] is put in by powershell when that object is empty or something.

$file = "c:\output.csv"

(gc $file) -replace "'system.object[]'", ""
[io.file]::readalltext($file).replace("'system.object[]'","")
(Get-Content $file | ForEach-Object { $_ -replace "system.object[]", "" } ) | Set-Content $file

Upvotes: 1

Views: 2357

Answers (3)

Pedro Isaaco
Pedro Isaaco

Reputation: 404

The bracers and the dot ([, ], .) need all to be escaped. Furthermore remove the double quotation marks, just keep the single ones. Also think about using creplace, in case you want to work case insensitive. So the command would look like this:

(gc $file) -replace 'system\.object\[\]', ''

In case you want to write everything to a new file:

(gc $file) -replace 'system\.object\[\]', ''|out-file "test2.txt" -encoding ASCII

Upvotes: 1

Avshalom
Avshalom

Reputation: 8899

Just use Escape character

(gc $file) -replace 'system.object\[\]', ""

The characters '[' and ']' are used for Regex pattern. You must use Escape character '\' to tell Powershell that This is a regular chars

Upvotes: 0

Ninja Cowgirl
Ninja Cowgirl

Reputation: 11281

I added following code to the variable that containing System.Object[] on output. and it's seems to be working. and now I dont have to do the replacement at file level.

"Access Code" = (@($AccessCode) | Out-String).Trim()

Upvotes: 1

Related Questions