[英]How can i get the sum of a line from a .txt file in powershell?
So, I have a textfile "numbers.txt" like this:所以,我有一个像这样的文本文件“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
My question is, how can i get the sum of each line?我的问题是,我怎样才能得到每行的总和? What i tried to do:
我试图做的事情:
$data=Get-Content -Delimiter " " numbers.txt
$data | % {
$sum=0
foreach($num in $_) {
$sum+=$num
}
Write-Host $sum
}
But it gives back weird numbers.但它返回了奇怪的数字。 I dont know how to separate the different numbers in each line and get the sum of them.
我不知道如何将每一行中的不同数字分开并得到它们的总和。
Here's a fast and concise PSv4+ solution that utilizes LINQ:这是一个使用 LINQ 的快速简洁的 PSv4+ 解决方案:
(Get-Content numbers.txt).ForEach({
[Linq.Enumerable]::Sum([int[]] ($_ -split ' '))
})
(Get-Content numbers.txt)
returns the input file's lines as an array of strings. (Get-Content numbers.txt)
将输入文件的行作为字符串数组返回。
.ForEach({ ... }
) executes a script block ( { ...}
) for each input line. .ForEach({ ... }
) 为每个输入行执行一个脚本块 ( { ...}
)。
[Linq.Enumerable]::Sum(...)
sums the elements of an array (enumerable) of numbers. [Linq.Enumerable]::Sum(...)
) 对数字数组(可枚举)的元素求和。
$_ -split ' '
splits the input line at hand ( $_
) into (string) tokens by spaces, and converts the result to an array of integers ( [int[]]
). $_ -split ' '
将手头的输入行 ( $_
) 按空格拆分为(字符串)标记,并将结果转换为整数数组 ( [int[]]
)。
Here's a - slower - solution closer to what you attempted (works in PSv3- too):这是一个 - 较慢 - 更接近您尝试的解决方案(也适用于 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
}
Both solutions yield the following:两种解决方案都会产生以下结果:
14 # 2 + 3 + 4 + 5
11 # 5 + 6
20 # ...
174
1128
126
As for what you tried :至于你尝试了什么:
Get-Content -Delimiter " " numbers.txt
This splits your entire file into a single array of number strings, ignoring line boundaries.这将您的整个文件到数字符串的单个阵列,忽略行边界。
Instead, you must use Get-Content
as-is in order to process the file line by line , and then split each line into space-separated tokens to sum up.相反,您必须按原样使用
Get-Content
以便逐行处理文件,然后将每一行拆分为以空格分隔的标记进行汇总。
Turn it into a single array of numbers:把它变成一个数字数组:
-split (get-content numbers.txt) | measure -sum | % sum
1473
Oops, sum each line:糟糕,对每一行求和:
get-content numbers.txt | foreach { -split $_ | measure -sum } | foreach sum
14
11
20
174
1128
126
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.