Home > Blockchain >  How to replace text in multiple file in many folder using powershell
How to replace text in multiple file in many folder using powershell

Time:12-26

I have many folder ex: folder1,folder2,folder3... about folder100

In those folder have many files ex: 1.html,2.html,3.html,4.html...about 20.html

I want to replace some text in those all html file in all folder but not all text i want to replace is same. ex:(for 1.html, i want to replace ./1_files/style.css to style.css) and (for 2.html, i want to replace ./2_files/style.css to style.css)....

So i try something like this and it work well

Get-ChildItem "*\1.html" -Recurse | ForEach-Object -Process {
    (Get-Content $_) -Replace './1_files/style.css', 'style.css' | Set-Content $_
}
Get-ChildItem "*\2.html" -Recurse | ForEach-Object -Process {
    (Get-Content $_) -Replace './2_files/style.css', 'style.css' | Set-Content $_
}
Get-ChildItem "*\3.html" -Recurse | ForEach-Object -Process {
    (Get-Content $_) -Replace './3_files/style.css', 'style.css' | Set-Content $_
}
Get-ChildItem "*\4.html" -Recurse | ForEach-Object -Process {
    (Get-Content $_) -Replace './4_files/style.css', 'style.css' | Set-Content $_
}

but i have to write many of those code "\4.html" "\5.html" "*\6.html" ...

i try this but it do not work

Do { 
    $val   
    Write-Host $val

    $Fn = "$val.html"

    Get-ChildItem "*\$Fn" -Recurse | ForEach-Object -Process {
        (Get-Content $_) -Replace './$val_files/style.css', 'style.css' | 
            Set-Content $_
    }
} while($val -ne 100) 

Please show me correct way to do..loop replace thanks you

CodePudding user response:

Assuming all your subfolders can be found inside one source folder path, you can do below to do the replacement in all those files:

# the path where all subfolders and html files can be found
$sourcePath = 'X:\Wherever\Your\Subfolders\Are\That\Contain\The\Html\Files'
Get-ChildItem -Path $sourcePath -Filter '*.html' -Recurse -File |
# filter on html files that have a numeric basename
Where-Object {$_.BaseName -match '(\d )'} | ForEach-Object {
    # construct the string to repace and escape the regex special characters
    $replace = [regex]::Escape(('./{0}_files/style.css' -f $matches[1]))
    # get the content as one single multiline string so -replace works faster
    (Get-Content -Path $_.FullName -Raw) -replace $replace, 'style.css' |
    Set-Content -Path $_.FullName
}
  • Related