Find the answer to your Linux question:
Results 1 to 5 of 5
Hi, there's some thing I just can't get going. After googling a while I didn't find any real clue, so hopefully some of you guys have some hint about this: ...
  1. #1
    Just Joined!
    Join Date
    Dec 2008
    Posts
    2

    Strings and floats in a bash script.

    Hi,

    there's some thing I just can't get going. After googling a while I didn't find any real clue, so hopefully some of you guys have some hint about this:

    There a re two files: ONE.TXT and TWO.TXT which contain floats - one for each line. To read the files into an array, I do this:

    DATA1=$(grep '' ONE.TXT)
    DATA2=$(grep '' TWO.TXT)

    Anything I do with these arrays works pretty fine. Until I try to compare the elements of each one, i.e. compare the first element of DATA1 with the first one of DATA2 a.s.o.
    Code looks like this:

    n=0
    for VAL1 in $DATA1; do
    let n=$n+1
    m=0
    for VAL2 in $DATA2; do
    let m=$m+1
    if [ $m -eq $n ]; then
    #----------------------------
    if [ VAL1 -ge VAL2 ]; then
    ....
    fi
    #----------------------------
    fi
    done
    done

    So.. I tried to some stuff to convert VAL1 and VAL2 into "integers" first, as the bash wants them, trying stuff like this:

    V1=`echo $VAL1/1 | bc -l`
    V1=$(expr $VAL1/1)

    to do afterwards:

    if [ $V1 -ge $V2 ]; then

    Nothing worked. To sum up the long speech: How do I convert a string in my $DATA1 into a number?


    Regards..

  2. #2
    tpl
    tpl is offline
    Linux User
    Join Date
    Jan 2007
    Location
    cleveland
    Posts
    452
    welcome to the forum

    bash may not be the best tool. You have two files

    one.txt
    a1
    b1
    c1
    .
    .
    .

    two.txt
    a2
    b2
    c2
    .
    .
    .

    you want to compare a1 with a2--> some action depending?

    use the "join" utility to get

    one.two.txt
    a1 a2
    b1 b2
    c1 c2
    . .
    . .
    . .

    then you can use "awk" to compare the a's, b's
    etc:

    awk '$1>$2 {print $1}' <one.two.txt
    the sun is new every day (heraclitus)

  3. #3
    Linux User
    Join Date
    Jun 2007
    Posts
    318
    If you need to compare two floats, use the bc utility as follows:

    Code:
    GE=`echo "if ($VAL1 >= $VAL2) print 1 else print 0" | bc -l`
    if [ $GE = 1 ]; then echo "greater than or equal"; fi

  4. #4
    Linux Newbie
    Join Date
    Jul 2008
    Posts
    181
    You can also use something slightly more simple, like

    Code:
    echo "1 < 2" | bc
    which will return 1 for true and 0 for false.

  5. #5
    Just Joined!
    Join Date
    Dec 2008
    Posts
    2
    So.. with your help my problem's solved now. Many thanks guys!

Posting Permissions

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