我在一個檔案夾中有 n 個文本檔案。每個檔案中只有一行文本。我必須從檔案夾中的每個檔案中洗掉前 500 個字符和后兩個字符。
使用 Powershell 怎么能做到這一點?
uj5u.com熱心網友回復:
使用該Substring()方法從該行中提取一個子字串:
# Read single line from file
$line = Get-Content file.txt -TotalCount 1
# Extract a substring starting from index 500 until two characters before the end
$truncatedLine = $line.Substring(500, $line.Length - 502)
# Write line back to file
$truncatedLine |Set-Content file.txt -Force
要針對給定檔案夾中的所有 txt 檔案運行,請使用Get-ChildItem發現檔案,然后使用ForEach-Object:
Get-ChildItem -Path .\path\to\folder -File -Filter *.txt |ForEach-Object {
$line = $_ |Get-Content -TotalCount 1
$truncatedLine = $line.Substring(500, $line.Length - 502)
$truncatedLine |Set-Content -LiteralPath $_.FullName
}
uj5u.com熱心網友回復:
例如,取出前 5 個數字和后 2 個數字。陣列索引從 0 開始。
$string = '1234567890'
-join $string[5..($string.length-3)]
678
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406812.html
標籤:
