Victor Nielsen
Victor Nielsen

Reputation: 493

How to “use” files with names that include certain text?

I'm importing files through a loop:

forvalues y=2010/2022 {
    use "file`y'V1.dta"
    [making changes]
    save “file`y'.dta”
}

Problem is that some of the filenames have "V2" or "V3" instead of "V1".

How can I "ignore" this part? In some programming languages, you just write “*” to indicate that anything can be in that spot in the string.

I cannot change the filenames in their original directory since they are on a shared server and they are too big to just copy.

Upvotes: 0

Views: 79

Answers (1)

Nick Cox
Nick Cox

Reputation: 37208

The most satisfactory solution is to loop over files file20??V?.dta which you can populate in Stata. Compare my answer at https://www.statalist.org/forums/forum/general-stata-discussion/general/1705910-loading-datasets-using-a-loop-with-an-inconsistent-naming-scheme

Otherwise, something like this may help. Necessarily not tested.

forvalues y=2010/2022 {
    capture use "file`y'V1.dta"
    if _rc { 
         capture use "file`y'V2.dta"
         if _rc {
              capture use "file`y'V3.dta" 
              if _rc { 
                  di "`y' data not found"
                  continue 
              }
         }
    }
   
    [making changes]
    save “file`y'.dta”
}

EDIT There are no concrete examples of directory or folder structure in your question. Nor do you state what operating system you are using. But let's suppose you are working in directory myplace but using files from otherplace. Forward slashes always work in Stata in this context.

local files : dir otherplace files "file20??V?.dta" 

foreach f of local files { 
    use otherplace/`f' 
    local year = substr("`f'", 5, 4)
    * changes 
    save otherplace/file`year'
} 

Upvotes: 1

Related Questions