簡短:我正在嘗試根據某個字串復制檔案夾中所有檔案中的行,然后僅替換重復行中的原始字串。
原始文本檔案的內容(檔案中有雙引號):
"K:\FILE1.ini"
"K:\FILE1.cfg"
"K:\FILE100.cfg"
僅當一行中存在字串“.ini”時,我才想將整行復制 4 次。
復制行后,我想將這些復制行中的字串(原始行保持不變)更改為:例如,“.inf”、“.bat”、“.cmd”、“.mov”。
所以腳本的預期結果如下:
"K:\FILE1.ini"
"K:\FILE1.inf"
"K:\FILE1.bat"
"K:\FILE1.cmd"
"K:\FILE1.mov"
"K:\FILE1.cfg"
"K:\FILE100.cfg"
這些檔案很小,因此不需要使用流。
我正處于我的 PowerShell 旅程的開始,但感謝這個社區,我已經知道如何遞回地替換檔案中的字串:
$directory = "K:\PS"
Get-ChildItem $directory -file -recurse -include *.txt |
ForEach-Object {
(Get-Content $_.FullName) -replace ".ini",".inf" |
Set-Content $_.FullName
}
但我不知道如何多次復制某些行并處理這些重復行中的多個字串替換。
然而 ;)
能指出我正確的方向嗎?
uj5u.com熱心網友回復:
要使用操作員實作此目的,-replace您可以執行以下操作:
#Define strings to replace pattern with
$2replace = @('.inf','.bat','.cmd','.mov','.ini')
#Get files, use filter instead of include = faster
get-childitem -path [path] -recurse -filter '*.txt' | %{
$cFile = $_
#add new strings to array newData
$newData = @(
#Read file
get-content $_.fullname | %{
#If line matches .ini
If ($_ -match '\.ini'){
$cstring = $_
#Add new strings
$2replace | %{
#Output new strings
$cstring -replace '\.ini',$_
}
}
#output current string
Else{
$_
}
}
)
#Write to disk
$newData | set-content $cFile.fullname
}
這將為您提供以下輸出:
$newdata
"K:\FILE1.inf"
"K:\FILE1.bat"
"K:\FILE1.cmd"
"K:\FILE1.mov"
"K:\FILE1.ini"
"K:\FILE1.cfg"
"K:\FILE100.cfg"
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/528433.html
標籤:电源外壳
