你好 StackOverflow 我想問你如何對輸入 file.txt 中每一行的奇數求和
input.txt 檔案看起來像這樣
4 1 8 3 7
2 5 8 2 7
4 7 2 5 2
0 2 5 3 5
3 6 3 1 6
輸出必須是
11
12
12
13
7
像這樣的代碼的開頭
read -p "Enter file name:" filename
while read line
do
...
我的代碼有什么問題
#!/bin/sh
read -p "Enter file name:" filename
while read line
do
sum = 0
if ($_ % 2 -nq 0){
sum = sum $_
}
echo $sum
sum = 0
done <$filename
uj5u.com熱心網友回復:
如果這就是您的 txt 檔案的設定方式,您可以使用Get-Content一些邏輯來完成此操作。
Get-Content將逐行讀取檔案(除非-Raw指定),我們可以通過管道將其Foreach-Object傳輸到 a以使迭代中的當前行 被空白分割。- 然后,我們可以評估新形成的陣列(由于拆分空白,留下數字以創建陣列)。
- 最后,只求奇數之和。
Get-Content -Path .\input.txt | ForEach-Object {
# Split the current line into an array of just #'s
$OddNumbers = $_.Split(' ').Trim() | Foreach {
if ($_ % 2 -eq 1) { $_ } # odd number filter
}
# Add the filtered results
($OddNumbers | Measure-Object -Sum).Sum
}
uj5u.com熱心網友回復:
你的問題的邏輯似乎是正確的,所以我會和你一起去,因為你不確定如何按照你的評論中的說明逐行做這件事。
if ($_ % 2 -nq 0){
sum = sum $_
}
我認為function在這種情況下這是一個好地方。將string包含integers作為輸入并回傳該字串上所有奇數的總和,或者-1假設沒有整數或所有偶數。
function Sum-OddNumbers {
[cmdletbinding()]
param(
[parameter(mandatory,ValueFromPipeline)]
[string]$Line
)
process
{
[regex]::Matches($Line,'\d ').Value | ForEach-Object -Begin {
$result = 0
} -Process {
if($_ % 2)
{
$result = $_
}
} -End {
if(-not $result)
{
return -1
}
return $result
}
}
}
用法
@'
4 1 8 3 7
2 5 8 2 7
4 7 2 5 2
0 2 5 3 5
3 6 3 1 6
2 4 6 8 10
asd asd asd
'@ -split '\r?\n' | Sum-OddNumbers
結果
11
12
12
13
7
-1
-1
uj5u.com熱心網友回復:
“這里有什么問題”:
while read line
do
sum = 0
if ($_ % 2 -nq 0){
sum = sum $_
}
echo $sum
sum = 0
done <$filename
首先,在分配中的sh周圍不允許有空格=
接下來if語法錯誤。見https://www.gnu.org/software/bash/manual/bash.html#index-if
另見https://www.gnu.org/software/bash/manual/bash.html#Shell-Arithmetic
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/363385.html
標籤:猛击
