Find the answer to your Linux question:
Results 1 to 4 of 4
Hello all. In this code I am reading points from a file which are separated by a space. It works for integers but points that contain negative or decimal numbers ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Jul 2012
    Posts
    9

    Won't read negative and decimal numbers -- bash


    Hello all. In this code I am reading points from a file which are separated by a space. It works for integers but points that contain negative or decimal numbers are ignored. How can I make it work with decimal and neg numbers?
    Thanks.

    ###################
    Code:
    IFS=$(echo -e "\n\r") # split on newlines instead of whitespace
    for LINE in $(grep "^[[:digit:]]\+ [[:digit:]]\+$" $1)
    do
        totalPoints=$(($totalPoints+1))
        IFS=" " read -a p$totalPoints <<< $LINE # set IFS to space to           
                                                                    # separate x & y
    done
    
    echo "Total points is $totalPoints"
    
    echo "P1: ${p1[@]}"
    echo "P2: ${p2[@]}"
    ###########

    Had to remove the "at" character in the [ ]"s to post on the forum. ??
    Last edited by atreyu; 04-10-2013 at 12:33 AM. Reason: added CODE tags to aid in readability and added "@" signs

  2. #2
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    Hi,

    Try egrep and this regular expression to match on possible negatives and decimals:

    Code:
    for LINE in $(egrep ^'-?[0-9][0-9]*\.?[0-9]* -?[0-9][0-9]*\.?[0-9]*'$ $1)
    do
    Last edited by atreyu; 04-10-2013 at 12:55 AM. Reason: added additional number range for integers > 9

  3. #3
    Just Joined!
    Join Date
    Jul 2012
    Posts
    9
    That did it! Thank you very much!

  4. #4
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    sweet - glad it's sorted. I'll mark this as Solved. You can always do the same using the Thread Tools link at the top of the page.

    cheers!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •