我從一個星期開始就加入了 powershell 社區,因此我遇到了一個小問題:我想瀏覽一個 txt 檔案并將每個 6 位數字的第一位更改為 8
例子:
舊檔案
2332
abc
234567
所需檔案
2332 (no change)
abc (no change)
834567 (change of the first digit to 8)
我已經嘗試過這段代碼,但是替換行有問題,找不到該行的正確語法
$original_file = "C:\original.txt"
$destination_file = "C:\new.txt"
(Get-Content $original_file) | Foreach-Object {
$_ -replace "(\d{1})(\d{5})", "8" "$2" } |
Set-Content $destination_file
感謝您提供急需的幫助!
uj5u.com熱心網友回復:
您可以使用:
$original_file = "C:\original.txt"
$destination_file = "C:\new.txt"
$file_content = Get-Content "$original_file"
Set-Content -Path "$destination_file" -Value ($file_content -replace "\b\d(\d{5})\b", "8`$1")
正則運算式將匹配:
\b- 匹配單詞邊界\d- 匹配一個數字(\d{5})- 匹配 5 位數字并在一組中捕獲它們\b- 匹配單詞邊界
然后將其替換為:
8- 數字 8- `$1 - 捕獲的組
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/381813.html
標籤:电源外壳
上一篇:并行運行一個函式并等待輸出
