Click here to Skip to main content
15,881,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Bash
shopt -s dotglob nullglob
shopt -s globstar 
for pathname in CWFiles/**/*.txt; do 
   [ ! -f "pathname" ] && continue

   while read -r line
   do 
      result=(( "$result" + "$pathname" ))
      echo $result

   done < "pathname" 
done


What I have tried:

I'm trying to calculate the total number >> result by adding each line to result
the problem is "pathname" can be sometimes a number with leading zeros.
the shell does not add octal number to integer as my error massage says.
how do I come around this problem even after trying $((10#"$pathname")) it didn't work.
Posted
Updated 19-Jan-22 11:19am
v2

1 solution

What you have posted here make no sense. As written, this line
Bash
result=(( "$result" + "$pathname" ))
, seems to be trying to accumulate something to result, but since you have
Bash
for pathname in CWFiles/**/*.txt
then pathname will hold a value something like CWFiles/foo/bar.txt. Clearly, that's not a number, so the attempt at addition is not going to work. It looks like you're trying to use integer math in a bash script, so you might want to use let or declare expressions instead. Incidentally, let expressions do octal math as expected:
Bash
[k5054@localhost tmp]$ let result=10
[k5054@localhost tmp]$ echo $result
10
[k5054@localhost tmp]$ let result+=10
[k5054@localhost tmp]$ echo $result
20
[k5054@localhost tmp]$ let result+=010  # octal addition
[k5054@localhost tmp]$ echo $result
28[k5054@localhost tmp]$
Maybe you want something more like:
Bash
shopt -s dotglob nullglob
shopt -s globstar
let result=0 
for pathname in CWFiles/**/*.txt; do
   [ ! -f "$pathname" ] && continue 

   while read -r line
   do 
      let result+=$line
      echo $result

   done < "$pathname" 
done
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900