【问题标题】:How to replace text in multiple file in many folder using powershell如何使用powershell替换多个文件夹中多个文件中的文本
【发布时间】:2022-01-25 10:49:06
【问题描述】:

我有很多文件夹 例如:文件夹1,文件夹2,文件夹3...关于文件夹100

在那些文件夹中有很多文件 例如:1.html,2.html,3.html,4.html...大约 20.html

我想替换所有文件夹中所有 html 文件中的一些文本 但并非我要替换的所有文本都是相同的。 例如:(对于 1.html,我想将 ./1_files/style.css 替换为 style.css)和(对于 2.html,我想将 ./2_files/style.css 替换为 style.css)... .

所以我尝试了这样的方法,效果很好

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

但我必须编写许多代码 "\4.html" "\5.html" "*\6.html" ...

我试试这个,但它不起作用

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) 

请告诉我正确的做法..循环替换 谢谢您

【问题讨论】:

  • 请添加您要更改的数据文件之一的示例以及结果的外观。请将其添加到您的问题中并以代码格式包装,以便人们可以轻松找到并阅读它。
  • -Replace './$val_files/style.css' --> -Replace "./$val_files/style.css"。不插入单引号字符串。
  • 顺便说一句,-Recurse 是多余的,因为它仅在 -Path 参数指向文件夹时才有效。您甚至可以将Get-ChildItem 替换为Get-Item

标签: powershell


【解决方案1】:

假设您的所有子文件夹都可以在一个源文件夹路径中找到,您可以执行以下操作来替换所有这些文件:

# 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
}

【讨论】:

  • 谢谢你这个工作很好,但你能向我解释一下 1. (\d+) 2. [regex]::Escape 和 {0} 和 $matches[1] 我是新来的在powershell中
  • 以及如何将字符串 (3.html) 转换为整数 (3) 然后 sub(-) 1 我试试这个 $string = "3.html" $integer = [int]$string -1 但不起作用
  • @rarksoca (\d+) 表示(正则表达式)在 $matches 对象中捕获 1 个或多个 digits[regex]::Escape() 是一种通过在该字符前面放置反斜杠来转义在正则表达式中具有特殊含义的字符(如点)的方法。 {0} 是一个占位符,将通过-f Format operator 填充。
  • @rarksoca 你不能对3.html 这样的字符串进行算术运算。您可以3 上执行此操作,方法是将其转换为[int]。在这种情况下,这就是 $matches[1] 值存储的内容(记住 (\d+) 正则表达式)
猜你喜欢
  • 2021-06-01
  • 2015-11-07
  • 2014-02-28
  • 1970-01-01
  • 1970-01-01
  • 2014-09-29
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
相关资源
最近更新 更多