user15190922
user15190922

Reputation: 11

BASH: Math with variable filled with data from Text file (Resolved)

I have spent some time trying and googling for the solution with no success. I have a text file, "file.txt" (Unix, BOM, LF) that contains 3 numbers, as follows:

7896763907428 40040000 14

I just need to do a simple math here:

7896763907428 + (40040000 * 14)

Doing that directly in bash (using Cygwin, btw) it works just fine:

echo $((7896763907428 + 40040000 * 14))
7897324467428

if I manually load the values into variables, it also works:

a=7896763907428
b=40040000
c=14

echo $((a + b * c))
7897324467428

However, if those values are in text file and I use them to do the math, it fails:

a=$(sed -n 1p auxFile.txt)
b=$(sed -n 2p auxFile.txt)
c=$(sed -n 3p auxFile.txt)
echo $((a + b * c))
bash: 7896763907428: syntax error: operand expected (error token is "7896763907428")

I've loaded the value using other methods, but they bring the same result. The weird stuff is that the failure happens only on $a, the math on $b and $b works.

echo $((b * c))
560560000
echo $((b + c))
40040014

EDIT: Original file came from windows PS exported as UTF8 option that end like been UTF8 + BOM that includes some data at the beginning of the file. Have used dos2unix tool to convert the text file before process it on linux.

Upvotes: 0

Views: 177

Answers (2)

0stone0
0stone0

Reputation: 43964

Numbers on single line (1 2 3)

If you're sure the file contains just 3 numbers, you can use read to capture those into a variable, and then use your variable test code;

#!/bin/bash

read n1 n2 n3 < file.txt

echo $((n1 + n2 * n3))

Try it online!

Numbers on seperate lines (1\n2\n3)

Set the internal field separator to a newline, and read as stated above;

#!/bin/bash

{ IFS= read -r n1 && IFS= read -r n2 && IFS= read -r n3; } < file.txt
echo $((n1 + n2 * n3))

Try it online! - Additional info

Upvotes: 0

Raman Sailopal
Raman Sailopal

Reputation: 12877

Since you are processing a file, awk maybe a better alternative:

awk '{ print $1 + ($2 * $3) }' file

Multiply the second space delimited field by the third and then add the first.

Upvotes: 1

Related Questions