Announcement

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

  • Combinig two loops into one

    Dear All,

    I'm creating a dta file with names of files within a folder of my local disk. To do so, I'm running the same loop twice, where the only change is the type of file I want to record in the dta file. I want to simplify the process in one loop, rather than two. This is my code.

    local paths ""C:\project1" "C:\project2" "C:\project3""
    foreach path of local paths {
    local fdir "`path'"
    cd "`path'"
    local files : dir . files "*.do"

    foreach file of local files {
    replace name= "`file'" if name==""
    set obs `=_N+1'
    }
    }

    foreach path of local paths {
    local fdir "`path'"
    cd "`path'"
    local files : dir . files "*.txt"

    foreach file of local files {
    replace name= "`file'" if name==""
    set obs `=_N+1'
    }
    }


    I tried inserting a new local macro within the first loop, but it yields repeated names of files.

    Thank you for your help in advance,

    Liz


  • #2
    This is closer to what you want, I think:

    Code:
    local paths `" "C:\project1" "C:\project2" "C:\project3" "'
    
    foreach path of local paths {
        cd "`path'"
    
        local files : dir . files "*.do"
    
        foreach file of local files {
            replace name= "`file'" if name==""
            set obs `=_N+1'
        }
    
        local files : dir . files "*.txt"
    
        foreach file of local files {
            replace name= "`file'" if name==""
            set obs `=_N+1'
        }
    }
    You do nothing with local macro fdir, so I don't bother with that.

    With fs (from SSC) you could do this:

    Code:
    local paths `" "C:\project1" "C:\project2" "C:\project3" "'
    
    foreach path of local paths {
        cd "`path'"
    
        fs *.do  *.txt  
    
        foreach file of local files {
            replace name= "`file'" if name==""
            set obs `=_N+1'
        }
    }

    Comment


    • #3
      (deleted, crossed in the ether)

      Comment


      • #4
        Also see filelist (from SSC) for a direct solution with no loops.

        Comment

        Working...
        X