0

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
1
  • this is work for my case. Get-ChildItem C:\Users\ThompsonHo\Desktop\testing *.txt -recurse | Foreach-Object { $c = ($_ | Get-Content) $c = $c -replace ',,','' [IO.File]::WriteAllText($_.FullName, ($c -join "rn")) } Commented May 15, 2018 at 2:46

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
$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
}

Comments

0

try this :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.