LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash: how to test for a number in Array within if loop? (https://www.linuxquestions.org/questions/programming-9/bash-how-to-test-for-a-number-in-array-within-if-loop-510653/)

realos 12-15-2006 06:22 AM

Bash: how to test for a number in Array within if loop?
 
---------------------------file.txt-----------------------------------
0
34
71
77
152
159
163
293
/END file.txt-------------------------------------------------------

I like to define an if loop with two possible branches depending on whether an integer is found in the error_block.txt file or not.

if [integer in file.txt]
then
command1;
else
command2;
fi

Following is my try at solving this problem but it does not work.

--------------------------------- myscript.sh----------------------------
/skipping

grep '^error' tracefile.txt | awk '{print $3}' > file.txt;

temp='cat file.txt | mawk '/34/{++count}END{print count}''

if [ $temp = 1 ]
then
printf "temp = 1";
else
printf "temp = 0";
fi

/END of myscript.sh------------------------------------------------

Q2) I like to avoid writing to file.txt file for speed purpos. How would I redirect output of the first command from myscript.sh to an array and use that array for testing in if construct.

Please note, that I am not just testing for occurence of a single number (namely 34) only. It is just a test. There is a while-do-done loop around the if construct that delivers different variables to be tested again their appearence in the file.txt.

Hope I could explain my problem. If something is not clear, please ask. I'd greatly appreciate your ideas.

Regards,

int0x80 12-15-2006 07:59 AM

Bash script:
Code:

#!/bin/bash
# findnum.sh by int0x80
# check if any numbers in the list exist in file

numbers="34 99 152 293 347";
for n in $numbers; do
    echo -n "$n?    ";
    if ! grep -q "^$n\$" $1
    then
        echo "No";
    else
        echo "Yes";
    fi
done

Usage:
Code:

int0x80:~/source/bash/fileio$ ./findnum.sh numbers.txt
34?    Yes
99?    No
152?    Yes
293?    Yes
347?    No

The numbers.txt file:
Code:

int0x80:~/source/bash/fileio$ cat numbers.txt
0
34
71
77
152
159
163
293



All times are GMT -5. The time now is 03:22 PM.