1

I'm relatively new in bash coding. I wrote a little script, that is a lopp through a txt file.

while read element1 element2 element3; do
if [ $element3 -lt 0.049 ]
then
operation
else
operation
fi
done < /path/file.txt

I am aware that the code above doesn't work for floats.

I would like to use one of the element of the txt file in an if statement, but this specific element is a decimal number.

I have also seen an example using awk, but I didn't understand it because using awk requires to change the code in non-familiar way to me.

So, is there a simple line of code to compare decimal numbers in if statements?

1

2 Answers 2

1

Here a simple solution using bc tool:

INPUT_VALUE=1.0
REF_VALUE=0.05

echo "${INPUT_VALUE} >= ${REF_VALUE}" | bc | grep -q 1

if [ $? == 0 ]; then
    echo "Greater or equal."
else
    echo "Lower."
fi
Sign up to request clarification or add additional context in comments.

Comments

0

Using awk to compare and add greater or lower to each line

VALUE=0.049
while IFS=" " read -r comp element1 element2 element3; do
  if [ "$comp" = "lower" ];then
     operation
  else
     operation
  fi
done < <(awk -v val="$VALUE" '{print ($3 < val ? "lower": "greater"),$0}' /path/file.txt)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.