[Solved] Arithmetic operations using numbers from grep


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

solved Arithmetic operations using numbers from grep