LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash script integer value problem [SOLVED] (https://www.linuxquestions.org/questions/programming-9/bash-script-integer-value-problem-%5Bsolved%5D-4175427200/)

luboiron 09-14-2012 03:50 AM

Bash script integer value problem [SOLVED]
 
Hello,
As a newbie in a shell scripting I have the following problem:

I am writing a bash script to read from file line by line. The problem is that I need to check every line form this file for some condition, and because the file is changing its length in time (log file for example) the number of the rows in it varies.
So I basically want to get the number of lines and add it in a "for" cycle, but it always gives an error, because it takes the number as a string and not as an integer value.
So the only thing I can't figure out how to do is to make the "for" cycle take the value as an integer in some way so it can process it.

Any help is greatly appreciated.

Thanks in advance!


Here is a sample of the code:
-----------------------------
#!/bin/bash
# get the number of rows in the file and print them on the screen
wc -l $FILE > $FILE2
cat $FILE2 | awk 'BEGIN { FS = " " } { print $1 } END { }'

# trying to enter manually the number of rows as an integer
echo -n "Enter the number above > "
read NUM1

# doing the for cycle
for i in {1..$NUM1}
do
if <read the $i line from file and check if something exists>
then
<do something>
else
<do other thing>
fi
done
-------------------------------

pan64 09-14-2012 04:00 AM

wc -l $FILE will itself print the number of lines
instead of: cat $FILE2 | awk '...' you can write awk '...' $FILE2
END { } can be ignored
If you want to combine them together you can also write: wc -l | awk 'BEGIN { FS = " " } { print $1 }'

But a single awk would be sufficient without anything else:
Code:

awk '
# $0 contains the current line
if # do some check
...
' $FILE

will work too

divyashree 09-14-2012 04:13 AM

In your for cycle you can mention like this:

Code:

for ((i=1;i<=NUM1;i++))
do
.
.
.
done


luboiron 09-14-2012 05:41 AM

Thanks a lot, divyashree, your suggestion done the trick!


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