Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

expr

Status
Not open for further replies.

malladisk

Programmer
Jun 14, 2001
69
US
Hi, I have a file with integers on each line and I want to sum them up.
What's wrong with the following code?

for x in `cat myfile.txt`
do
total=`expr $total + $x`
done
echo $total

I keep getting "expr: Systax error"

Thanks,
SM
 
Code:
#!/bin/ksh

typeset -i total=0;

for i in $(< myfile.txt) ; do
  total=$(expr ${total} + ${i})
done

echo "total->[${total}]"

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
If not in ksh like shell:
for x in `cat myfile.txt`
do
total=`expr ${total:=0} + $x`
done
echo $total

In a ksh like shell:
typeset -i total=0 x=0
for x in $(< myfile.txt); do ((total+=x}); done
echo $total

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Hi malladisk,

>>> What's wrong with the following code?

The expr command requires $total and $x to exist so that it can add them together. The syntax error is caused because $total doesn't exist on the first time through the for loop. So just put the line:
total=0

before the for loop.

I hope that helps.

Mike
 
Oops, sorry for the typo :~/
In a ksh like shell:
typeset -i total=0 x=0
for x in $(< myfile.txt); do ((total+=x)); done
echo $total

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Thanks, guys! :) I find Vlad's tip extremely useful, that of using typeset so that I don't have to use expr again!
Sashi
 
Vlad/PHV:

Could either of you comment on the use of:

for i in `cat filename`

versus:

for i in $(< filename)

The second one really isn't a useless use of cat, UUOC, because it doesn't spawn another shell. Is that correct?

Thanks!


Ed
 
olded, I'm not sure.
manKSH said:
The command substitution $(cat file)
can be replaced by the equivalent $(<file). Command substitution
of most special commands that do not perform input/output
redirection is carried out without creating a separate process.

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top