我想替換文本檔案中以值 STRING: 開頭的行。我想用 STRING: 替換每個文本檔案的這一行:后跟不帶擴展名的檔案名。
$src = "C:\Input"
Get-ChildItem $src -recurse -include *.mi |
Select -expand fullname |
ForEach-Object {
(Get-Content $_) -replace "STRING: . ","STRING: $($_.BaseName)" |
Set-Content $_
}
我的腳本沒有添加檔案名,它只用字串替換了該行:
STRING: text to be replaced
變成
STRING:
雖然它應該是
STRING: filename
如何在替換操作中包含檔案名?
uj5u.com熱心網友回復:
只需洗掉Select -expand fullname命令,您就可以在腳本塊中獲得完整的FileInfo物件,即 的輸出:Get-ChildItem$_ForEach-Object
$src = "C:\Input"
Get-ChildItem $src -file -recurse -include *.mi |
ForEach-Object {
(Get-Content $_.FullName) -replace "STRING: . ","STRING: $($_.BaseName)" |
Set-Content $_.FullName
}
我還添加了-fileswitch 以Get-ChildItem明確我們希望它回傳的內容。可能有名為 like 的檔案夾*.mi,在您的情況下這可能不是問題,但通常使用-file更安全。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/496658.html
