hello the StackOverflow i wanted to ask you how to sum the odd numbers in every line from input file.txt
the input.txt file looks like that
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
the output must be
11
12
12
13
7
start of the code like this
read -p "Enter file name:" filename
while read line
do
...
my code whats the wrong here
#!/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
CodePudding user response:
If that's how your txt file is set up, you can use Get-Content
and a bit of logic to accomplish this.
Get-Content
will read the file line by line (unless-Raw
is specified), which we can pipe to aForeach-Object
to have the current line in the iteration split by the white space.- Then, we can evaluate the newly formed array (due to splitting the white space, leaving the numbers to create an array).
- Finally, just get the sum of the odd numbers.
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
}
CodePudding user response:
The logic seems correct on your question so I'll go with you're not sure how to do this line by line as stated on your comment.
if ($_ % 2 -nq 0){
sum = sum $_
}
I think it's a good place for a function
in this case. Takes a string
containing integers
as input and returns the sum of all odd numbers on that string or -1
assumming there are no integers or all even numbers.
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
}
}
}
Usage
@'
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
Result
11
12
12
13
7
-1
-1
CodePudding user response:
"what's wrong here":
while read line
do
sum = 0
if ($_ % 2 -nq 0){
sum = sum $_
}
echo $sum
sum = 0
done <$filename
First, in sh
, spaces are not allowed around the =
in an assigmnent
Next the if
syntax is wrong. See https://www.gnu.org/software/bash/manual/bash.html#index-if
See also https://www.gnu.org/software/bash/manual/bash.html#Shell-Arithmetic