![](/img/trans.png)
[英]How can I get a output from a powershell function into a output file for example txt?
[英]How can i get the sum of a line from a .txt file in powershell?
所以,我有一個像這樣的文本文件“numbers.txt”:
2 3 4 5
5 6
6 7 7
6 88 9 67 4
65 76 979 8
6 88 5 4 23
我的問題是,我怎樣才能得到每行的總和? 我試圖做的事情:
$data=Get-Content -Delimiter " " numbers.txt
$data | % {
$sum=0
foreach($num in $_) {
$sum+=$num
}
Write-Host $sum
}
但它返回了奇怪的數字。 我不知道如何將每一行中的不同數字分開並得到它們的總和。
這是一個使用 LINQ 的快速簡潔的 PSv4+ 解決方案:
(Get-Content numbers.txt).ForEach({
[Linq.Enumerable]::Sum([int[]] ($_ -split ' '))
})
(Get-Content numbers.txt)
將輸入文件的行作為字符串數組返回。
.ForEach({ ... }
) 為每個輸入行執行一個腳本塊 ( { ...}
)。
[Linq.Enumerable]::Sum(...)
) 對數字數組(可枚舉)的元素求和。
$_ -split ' '
將手頭的輸入行 ( $_
) 按空格拆分為(字符串)標記,並將結果轉換為整數數組 ( [int[]]
)。
這是一個 - 較慢 - 更接近您嘗試的解決方案(也適用於 PSv3-):
Get-Content numbers.txt | ForEach-Object { # Process each line.
$sum = 0 # initialize the sum (implicitly of type [int])
foreach ($num in $_ -split ' ') { # Process all tokens on the line.
# Note: Because $sum is [int]-typed, adding the *string* token at
# hand implicitly converts it to [int].
$sum += $num
}
$sum # Output the sum - do NOT use Write-Host to output DATA
}
兩種解決方案都會產生以下結果:
14 # 2 + 3 + 4 + 5
11 # 5 + 6
20 # ...
174
1128
126
至於你嘗試了什么:
Get-Content -Delimiter " " numbers.txt
這將您的整個文件到數字符串的單個陣列,忽略行邊界。
相反,您必須按原樣使用Get-Content
以便逐行處理文件,然后將每一行拆分為以空格分隔的標記進行匯總。
把它變成一個數字數組:
-split (get-content numbers.txt) | measure -sum | % sum
1473
糟糕,對每一行求和:
get-content numbers.txt | foreach { -split $_ | measure -sum } | foreach sum
14
11
20
174
1128
126
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.