Monday, March 25, 2013

24 - Counting number of lines in a file within FORTRAN code

If you want to determine the number of line in a given file within your FORTRAN code,
you can do this following nice trick!

program count_lines
   implicit none
   integer:: n
   character(len=60):: cmd
    cmd = "cat file_name.dat | grep '[^ ]' | wc -l > nlines.txt"
    call system(cmd)
    open(1,file='nlines.txt')
    read(1,*) n
    print*, "Number of lines are", n 
    cmd = 'rm nlines.txt'
    call system(cmd)
end program

This simple code, uses linux command to find the number of lines.
Notice that  cat file_name.dat | grep '[^ ]' | wc -l  returns the number of lines in a file with ignoting the blank lines.

1 comment:

  1. above program is which version of fortran. what should be the file extension.

    ReplyDelete