Powershell递归查找文件并替换文件中的字符串
Powershell to find file and replace a string in file recursively
我想递归搜索特定 属性 文件的路径。找到文件后,我想搜索模式“@1.0.0”并替换为“@2.0.0”
我的脚本找到了文件和字符串,但无法替换为较新的字符串。
$RevString=Get-ChildItem -Path $buildFilePath -Filter package.json
-Recurse | Select-String -Pattern "@1.0.0"
这会将结果显示为
C:\..\package.json:21:
"hl-common-ui-components@1.0.0", C:\..\package.json:21:
"hl-common-ui-components@1.0.0",
我尝试了以下方法来替换但它不起作用
ForEach ($i in $RevString) {
(Get-Content $i) |
Foreach-Object {$_ -replace "@\d.\d.\d","@$major.$minor.$patch" } |
Set-content ($i)
}
改变
$RevString=Get-ChildItem -Path $buildFilePath -Filter package.json -Recurse | Select-String -Pattern "@1.0.0"
到
$RevString=Get-ChildItem -Path $buildFilePath -Filter package.json -Recurse | Select-String -Pattern "@1.0.0" -List | Select-Object -ExpandProperty Path
-List
参数为 Select-String
"returns only the first match in each input file"。 Select-Object -ExpandProperty Path
表示我们只需要包含匹配字符串的文件的完整路径。 $RevString
现在将只包含文件名。
Select-String
returns MatchInfo 对象。它们有几个属性,包括 LineNumber、Line、Filename 和 Path。如果将输出管道化到 Select-Object *
,您可以看到所有这些,如:
Select-String -Pattern "@1.0.0" -List | Select-Object *
我想递归搜索特定 属性 文件的路径。找到文件后,我想搜索模式“@1.0.0”并替换为“@2.0.0” 我的脚本找到了文件和字符串,但无法替换为较新的字符串。
$RevString=Get-ChildItem -Path $buildFilePath -Filter package.json
-Recurse | Select-String -Pattern "@1.0.0"
这会将结果显示为
C:\..\package.json:21:
"hl-common-ui-components@1.0.0", C:\..\package.json:21:
"hl-common-ui-components@1.0.0",
我尝试了以下方法来替换但它不起作用
ForEach ($i in $RevString) {
(Get-Content $i) |
Foreach-Object {$_ -replace "@\d.\d.\d","@$major.$minor.$patch" } |
Set-content ($i)
}
改变
$RevString=Get-ChildItem -Path $buildFilePath -Filter package.json -Recurse | Select-String -Pattern "@1.0.0"
到
$RevString=Get-ChildItem -Path $buildFilePath -Filter package.json -Recurse | Select-String -Pattern "@1.0.0" -List | Select-Object -ExpandProperty Path
-List
参数为 Select-String
"returns only the first match in each input file"。 Select-Object -ExpandProperty Path
表示我们只需要包含匹配字符串的文件的完整路径。 $RevString
现在将只包含文件名。
Select-String
returns MatchInfo 对象。它们有几个属性,包括 LineNumber、Line、Filename 和 Path。如果将输出管道化到 Select-Object *
,您可以看到所有这些,如:
Select-String -Pattern "@1.0.0" -List | Select-Object *