Home > Software design >  Arithmetic operations using numbers from grep
Arithmetic operations using numbers from grep

Time:09-26

I have FILE from which I can extract two numbers using grep. The numbers appear in the last column.

 $ grep number FILE 
 number1:    123
 number2:    456

I would like to assign the numbers to variables, e.g. $num1 and $num2, and do some arithmetic operations using the variables.

How can I do this using bash commands?

CodePudding user response:

Assumptions:

  • we want to match on lines that start with the string number
  • we will always find 2 matches for ^number from the input file
  • not interested in storing values in an array

Sample data:

$ cat file.dat
number1: 123
not a number: abc
number: 456

We'll use awk to find the desired values and print all to a single line of output:

$ awk '/^number/ { printf "%s ",$2 }' file.dat
123 456

From here we can use read to load the variables:

$ read -r num1 num2 < <(awk '/^number/ { printf "%s ",$2 }' file.dat)

$ typeset -p num1 num2
declare -- num1="123"
declare -- num2="456"

$ echo ".${num1}.${num2}."
.123.456.

NOTE: periods added as visual delimiters

CodePudding user response:

Firstly, you need to extract the numbers from the file. Assuming that the file is always in the format stated, then you can use a while loop, combined with the the read command to read the numbers into a named variable, one row at a time.

You can then use the $(( )) operator to perform integer arithmetic to keep a running total of the incoming numbers.

For example:

#!/bin/bash

declare -i total=0           # -i declares an integer.

while read discard number; do # read returns false at EOF. discard is ignored.
  total=$((total number))     # Variables don't need '$' prefix in this case.
done < FILE                   # while loop passes STDIN to the 'read' command.

echo "Total is: ${total}"
  • Related