Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
how can I do computations on values that are stored within a file?? For example if "file1" contains the number 5 and "file2" contains the number 2, how do I write a script that multiplies these two values together and gives me the desired output of 10?? Any help would be greatly appreciated...

The more specific you can be about your data, the better answers you will get.
Following uses awk to isolate a specific line in both file1 and file2, and pulls one field from each of those lines.
# !/bin/ksh
a=`awk '$1=="A"{print $2;exit}' file1`
b=`awk '$1=="B"{print $3;exit}' file2`echo "a=$a"
echo "b=$b"
echo "a times b = $((a*b))"exit 0
You can use several commands other than awk to read the desired line from your files and cut the desired field (cat, grep, cut, sed) depending on your files. Some examples:
a=`cat file1`
a=`head -1 file1`
a=`grep ABC file1 | cut -c22-28`
head -1 file1 | read word1 word2 a rem

Okay, that's great...now one more thing, it's showing in 8/9 = 0 and 9/8 = 1...It's obviously in integer format...how do I make it display three decimal places...like (0.889 or 1.125)?? Thanks again!!

I would say you need to use the calc function. Its a little slower but will give you the decimal numbers. You can use calc and cut to isolate what you need
and take out the ~ that calc puts in its answers with decimalsSo you could do.
a=8
b=9
total=`calc "$a / $b" | cut -c 1-6 | tr -d "[~]"And that would give you the answer of: .8888

I tried this but it doesn't work...It says:
a=8
b=9
c=calc "$a / $b" | cut -c 1-6 | tr -d "[~]"
ksh: calc: not foundCan this command be done in korn shell??

You need the ` at the beginning and the end of the line
so:
c=`calc "$a / $b" | cut -c 1-6 | tr -d "[~]"`

Modify this script to do what you want. I use bc to get floating point results.
#!/bin/ksh
#################
function calc { #
#################print "Enter a number (can be a decimal): \c"
read FirstNumprint "Enter a number (can be a decimal): \c"
read SecondNumprint "Enter an operator ( + - / * ): \c"
read Operator # Oh can you help me make this call.case $Operator in
+ | - | / | \* ) continue
;;
* ) print "Invalid operator"; return 99
;;esac
result=$(print "scale = 2; $FirstNum $Operator $SecondNum" | bc )
print $result
} # end of the calc function.
calc

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |