Trix & Graphix

Reading a file until it ends

It is a commont task that you have to read some information from a file to perform some calculations. This uses to be done inside a loop. The problem is that many times you don't know how many lines the file has, so you can't use a counter as the condition to stop reading. Or maybe you know, but you don't want to pass that information to the program every time you run it. In this post I'm showing how to "teach" a Fortran and Bash program to read until it reach the end of the file.

Fortran version
In fortran, you have to use the option iostat when you use the read function. By doing so, there is an integer variable (ierr in the example below) that contains the output code of the last read action. If it is different to 0, it means that the end of the files has been reached (or something even worse). I think the example is self explanatory

program readtotheend
implicit none
integer :: i, ierr, number
do while(ierr.eq.0)
print*, 'Element', i, number
print*, 'Reading finished', i-1, 'lines'
end program

Bash version
The Bash version of this idea is to use a while loop and feed it with the input file

set -ex
while read number; do
# Here you can do whatever you want to do with the variable, which is stored in the variable number
done < filein.asc

This is a really elegant solution to perform some operation to all the lines of a file.

Generating random numbers within a Bash script

Unix systems has their own random numgers generator. It can be employed, for instance, to generate a sequence of random numbers inside a Bash script. The only thing that has to be done is to use the internal function $RANDOM

The next example illustrates the idea:

set -ex

for i in $(jot 100 1 1); do
echo $RANDOM >> file