當我從“C:\myfolder”運行此腳本時,我在 C:\myfolder*.txt 中有 100 多個 txt 檔案,我可以將第八行和第九行添加到 somename.txt
@echo off
powershell "$f=(Get-Content somename.txt);$f[8]='heretext1';$f | set-content somename.txt"
powershell "$f=(Get-Content somename.txt);$f[9]='heretext2';$f | set-content somename.txt"
但是我怎樣才能將第八行和第九行添加到路徑 C:\myfolder*.txt 中的所有 *.txt 檔案中有人可以解釋一下我該怎么做...
uj5u.com熱心網友回復:
也許像這個 PowerShell 腳本這樣的東西適合您的任務:
Get-ChildItem -Path 'C:\myfolder' -Filter '*.txt' | ForEach-Object {
$LineIndex = 0
$FileContent = Switch -File $_.FullName {Default {
$LineIndex
If ($LineIndex -Eq 8) {@'
heretext1
heretext2
'@}
$_}}
Set-Content -Path $_.FullName -Value $FileContent}
uj5u.com熱心網友回復:
筆記:
您的代碼不是添加行,而是修改現有行。下面的解決方案也是如此。
索引
[8]并[9]訪問第9 行和第 10行,而不是第8 行和第 9行,因為陣列索引是0基于 - 的。
您需要Get-ChildItem使用檔案名模式呼叫C:\myfolder\*.txt,并通過以下方式處理每個匹配的檔案ForEach-Object:
@echo off
powershell "Get-ChildItem C:\myfolder\*.txt | ForEach-Object { $f=$_ | Get-Content -ReadCount 0; $f[8]='heretext1'; $f[9]='heretext2'; Set-Content $_.FullName $f }"
由于從批處理檔案 ( cmd.exe) 呼叫,PowerShell 命令在單行中指定;這是可讀版本:
Get-ChildItem C:\myfolder\*.txt | # get all matching files
ForEach-Object { # process each
$f = $_ | Get-Content -ReadCount 0 # read all lines
$f[8] = 'heretext1'; $f[9] = 'heretext2' # update the 9th and 10th line
Set-Content $_.FullName $f # save result back to input file
}
筆記:
考慮添加
-noprofileafterpowershell,以抑制可能不必要的組態檔加載- 請參閱 Windows PowerShell CLI 的檔案,powershell.exe.使用
-ReadCount 0withGet-Content大大加快了處理速度,因為所有行都被讀入單個陣列,而不是逐行流式傳輸,這需要將它們收集到一個陣列中,這要慢得多。注意:如果給定檔案的行數少于10 行,上述解決方案將不起作用,因為您只能分配給陣列的現有元素(陣列是固定大小的資料結構)。如果您需要處理這種情況,請在該
$f = $_ | Get-Content -ReadCount 0行之后插入以下內容:if ($f.Count -lt 10) { $f = @('') * (10 - $f.Count) }
uj5u.com熱心網友回復:
我能想到的最簡單的解決方案是使用為此-Index提供的引數Select-Object。
Get-ChildItem -Path .\Desktop\*.txt | % { Get-Content $_.FullName | Select-Object -Index 7,8 } |
Out-File -FilePath .\Desktop\index.txt
編輯:根據您的帖子。
uj5u.com熱心網友回復:
對不起我的英語,對不起,如果我沒有解釋我的問題。我現在試試:
我使用“*.uci”檔案,而不是*.txt 檔案。我寫了 txt 因為大多數人都不知道 uci 擴展。這些 *.uci 檔案是使用 uci 協議的國際象棋引擎的設定。因此,當您使用 chessbase 程式時,您有很多國際象棋引擎,每個引擎都會創建它們的“enginename.uci”檔案。如果您想將 PC 上使用的核心數量從 1 更改為 16,您需要通過在 *.uci 檔案中添加以下資訊來手動完成,如下所示:
[OPTIONS]
Threads=1
這就是為什么最好通過一鍵添加這兩行來制作小批量或ps1來更改所有引擎的設定
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515736.html
標籤:电源外壳批处理文件命令
