Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search and replace

Status
Not open for further replies.

underthewood

Programmer
Nov 8, 2010
4
Hey, im afraid Ive got another question!

What I need to do is compare two text files that have identical formatting.
Both files have this sort of format as column headings:

n1 n2 n3 n4 n5 n6 <NUMBER>


One of the files is a complete list, with these as the headings, and values go down the list in increasing order of n1. The other file has a list under these headings, but there are substantial rows missing.
However, in the incomplete list, there will be a row with n1, n2, n3, n4, n5, n6 corresponding to another row in the complete list. The only thing different is the <NUMBER>.

Is there are a way of taking a row from one list, matching it with the same format in the other list, and replacing the entire row in that other list (ie replacing the <NUMBER> for a given n1, n2, n3, n4, n5, n6)?

Thanks
 
It is not very easy to change something in a sequential text file. This is not related to FORTRAN but simply a sequential file issue.

The only way to proceed is to create a new file which will contain the modifications. After that, is is possible to copy the new file into the old one.

Here is my proposed solution for your problem if you want to change only one row starting by a specific string :

Code:
PROGRAM test

   IMPLICIT NONE
   
   INTEGER,PARAMETER :: maxlen=512 ! maximum row length
   CHARACTER(maxlen) :: search,refrow,row
   INTEGER :: n
   
   WRITE(*,*) 'enter the searched string'
   READ(*,'(A)') search
   n=LEN_TRIM(search)

   ! looking for the string in the reference file
    
   OPEN(15,file="reference.txt",form='FORMATTED',status='OLD')
   
   DO
      READ(15,'(A)',end=1000) refrow
      IF(refrow(1:n) == search(1:n)) EXIT
   ENDDO

   ! creating a temporary file equal to the
   ! incomplete file except for one row
    
   OPEN(16,file="incomplete.txt",form='FORMATTED',status='OLD')
   OPEN(17,form='FORMATTED',status='SCRATCH')
   DO
      READ(16,'(A)',end=20) row
      IF(row(1:n) == search(1:n)) THEN
        WRITE(17,'(A)') TRIM(refrow)  ! writing the reference row
      ELSE
        WRITE(17,'(A)') TRIM(row)     ! writing the current row
      ENDIF
   ENDDO
20 CONTINUE

  ! Copying back the temporary file in the incomplete file
  
   REWIND(16)
   REWIND(17)
   DO
      READ(17,'(A)',end=30) row
      WRITE(16,'(A)') TRIM(row)
   ENDDO
   
   30 CONTINUE
   
   STOP
   
   1000 CONTINUE
   
   WRITE(*,*) "Impossible to find the string ",search(1:n)
   
END PROGRAM

François Jacq
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top