Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Automating the editing of multiple do files in a folder

    Dear Statalister,

    I have a do file ("old_file") that contains references to multiple file pathways:

    Code:
    do "C:\Users\Lukasz\Documents\Stata\do_file_1"
    
    do "C:\Users\Lukasz\Documents\Stata\do_file_2"
    
    do "C:\Users\Lukasz\Documents\Stata\do_file_3"
    I wish to write some code that opens this do file and replaces any lines that contain a reference to a file pathway with the string "some_string"

    Like so:
    Code:
    "some_string"
    
    "some_string"
    
    "some_string"
    I have tried using filefilter, but I can't seem to make it general enough (e.g., file pathways might vary). If it could incorporate a wildcard function it would suit my purposes but I'm not sure if it does. Or at least I haven't been able to implement it.

    I suspect that the solution lies in using the file command but I can't quite work it out. I have tried adapting some code from this thread (https://www.statalist.org/forums/for...file-command):

    Code:
     // open new output file to receive edited do-file
     file open new_file using "new_file.do", write text replace
     // open do-file to edit
     file open old_file using "old_file.do", read text
     // read the first line, which won't be an end-of file
     file read old_file line
     // if the last line wasn't the last
     while r(eof)==0 {
    
         // if line contains "C:\" replace with some string
         if strpos(`line', "C:\") == 1 {
            file write new_file "some_string"' _newline
             }
         else {
             file write new_file `line' _newline
             }
         file read old_file line
    }
    file close new_file
    file close old_file
    But it returns "do"C:\Users\Lukasz\Documents\Stata\do files" invalid name r(198);"

    From what I can figure out, it seems like the local macro `line' doesn't stores the entirety of the line from "old_file" in a string format, which prevents the string function from working. I have tried displaying/converting the the local macro `line' into a string using "local string_line : di %40s `line" and applying the string function to that macro instead, but that doesn't work. There might be other issues as well.Can this code be modified to achieve what I want or is there some other method?

    Any help would be much appreciated

    Lukasz

Working...
X