0

I want to input values like "2.1", "1.2", "143.22",... So something with this format: number1.number2

So far I have this code to separate number1 and number2.

echo -n "Enter value:  "
read answer

left=`echo $answer | awk -F "." '{print $1}'`      # number1
right=`echo $answer | awk -F "." '{print $2}'`     # number2

I don't want the user to input something like "1.2.3". How do I check if the user has entered an extra value?

I am thinking of something like this:

i=3

while true; do

    if [ -z "`echo $answer | awk -F "." '{print $i}'"]; then
        echo "Invalid input"

    i=$((i+1))
done

Will this work?

3
  • 2
    Hint: You could check for the number of fields, i.e. NF, using awk. Commented Jun 26, 2014 at 13:43
  • @devnull Will try. But will awk be able to distinguish the delimiter .? Commented Jun 26, 2014 at 13:46
  • Yes. You can specify the delimiter as .. Commented Jun 26, 2014 at 13:50

1 Answer 1

2

You can simplify the test using an expression like this:

if [[ $answer =~ ^[0-9]+\.[0-9]+$ ]]; then ... fi

HTH, Marcello

Sign up to request clarification or add additional context in comments.

3 Comments

Can you give an explanation for the regular expression
^=start of string.....[0-9]+=any number from 1 to 9 and the + means one or more occurences..... \.=just a dot backslash escaped..... $= end of string
[0-9] is a digit (you could use [[:digit:]] instead); + means "one or more"; . is a wildcard, but we need it as a character, so we quote it using the `; ^` and $ means begin and end

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.