Perform Arithmetic Operations On Two Files

In this Blog , we will cover how to apply sum ,multiply or subtract operator on two files each having one field and same number of records. Consider the data in each file as below.

Below is the Shell script which will multiply row by row from above two files and put the output in another file.

arr1=()
for line in cat linux.txt | tail -n+2
do
arr1+=("$line")
done
arr1_1=()
for line in cat linux_1.txt | tail -n+2
do
arr1_1+=("$line")
done
LenOfArr= ${#arr1[@]}
touch newfile.txt
echo "COL1" > newfile.txt
a=0
while [ $a -le $((LenOfArr-1)) ]; do let ans=${arr1[a]}*${arr1_1[a]}; echo $ans >> newfile.txt; a=$(( $a + 1 )); done

When you execute the above code, newfile.txt will be created with data of each row from both the files is multiplied. Here, array is used and data is stored in that array from file.

Takeaways from this Blog :
1. Array Creation.
2. Usage of Array Elements & Length of an Array.
3. Sum,multiply,subtract operations on Array Elements.


Related posts