Please, can someone share with me, or show me the script for Linux command to read from a file until EOF and compute the square of all numbers read. The result of this computation must be stored in an output file.

  • 7
    This site is designed for people to help others, not to do the work for them. You are expected to make sufficient effort in solving it yourself. I would probably do it with a for num in... and use expr for the calculation, redirecting its output to the proper file (>>output). Now that you have 80% of the work done, can you complete it? – Julie Pelletier Jun 26 '16 at 5:11
$ echo 3.14 >> /tmp/numbers
$ echo 2 >> /tmp/numbers
$ echo 4.0 >> /tmp/numbers

$ awk '{print $1 * $1}' < /tmp/numbers
$ awk '{print $1 * $1}' < /tmp/numbers > /path/to/OutputFile

Using ksh93 and bc as a compute service, assuming the file numbers contain one number on each line:

bc -l |&

while read num; do
    print -p "$num * $num"
    read -p sqr
    printf '%g*%g = %g\n' "$num" "$num" "$sqr"
done <numbers

kill "$bc_pid"

The equivalent thing in bash:

coproc bc -l

while read num; do
    printf '%g * %g\n' "$num" "$num" >&"${COPROC[1]}"
    read sqr <&"${COPROC[0]}"
    printf '%g*%g = %g\n' "$num" "$num" "$sqr"
done <numbers

kill "$bc_pid"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.