Thompson Ho
Thompson Ho

Reputation: 71

How to do replace on multiple files with powershell

The aim is replace ",," with blank in the text files. enter image description here

The below works on single file:

$path = "C:\Users\ThompsonHo\Desktop\testing\F181RMR CAN.txt"
$word = ",,"
$replacement = ""
$text = get-content $path 
$newText = $text -replace $word,$replacement
$newText > $path

I try to make it handle for multiple files but fail, How to do replace on multiple files with powershell?

$path = "C:\Users\ThompsonHo\Desktop\testing\F18*.txt"
$word = ",,"
$replacement = ""
$text = get-content $path 
$newText = $text -replace $word,$replacement
$newText > $path

Upvotes: 0

Views: 164

Answers (3)

Esperento57
Esperento57

Reputation: 17472

try this :

Get-ChildItem "c:\temp\F18*.txt" | %{$file=$_.FullName; (Get-Content $file).Replace(',,', ',') | Out-File $file }

Upvotes: 0

qdl
qdl

Reputation: 11

$p="C:\temp"
$cs=Get-ChildItem -Path $p 

foreach($c in $cs)
{
    $t=Get-Content -Path $c.FullName -Raw 
    #$t  -replace ",,",""|Out-File -FilePath  $c.FullName -NoNewline
    Set-Content -Path $c.FullName -Value ($t  -replace ",,","") -NoNewline
}

Upvotes: 0

Daniel Mann
Daniel Mann

Reputation: 59020

You have to retrieve a list of files, then iterate over the list.

You can retrieve files that match a pattern with Get-ChildItem (although Get-Item would also work in this situation):

$files = Get-ChildItem "C:\Users\ThompsonHo\Desktop\testing\F18*.txt"

That gives you an array of FileInfo. You can iterate over a collection with foreach.

foreach ($file in $files) {
    $file.FullName
}

$file.FullName at this point will be the full path to the file.

Your existing working solution for a single file should be easy to adapt.

Upvotes: 1

Related Questions