问题
I am working with Stata and am a beginner. I have a question regarding grabbing folder names. I have a directory, \Test\abc, that has the following folders like this:
Q100
Q101
Q102
....
I would like to go into each folder, Q* (where * denotes anything after the Q), find a file named "filenameQ*", do something, and then send the output back to \Test\abc. The following code shows the idea of what I want to do, where varlist Q* denotes the array of all the folders in the directory that begin with Q. However, folder names aren't variables, so I'm not sure how to proceed.
cd "\\Test\abc"
foreach x of varlist Q* /* FOLDER NAMES */ {
cd "`x'"
use "filename`x'"
display something and send it back to directory "\\Test\abc"
cd ..
}
回答1:
There is a user-written command called folders
that will store the names of folders in a local r(folders). There is another command called fs
that does the same for files.
Here's an example of how you might do this (given your ordering constraint in the comments):
capture ssc install fs, replace
cd "~/Desktop/Test/abc"
/* Get a list of years to loop over by stripping out Q[0-9] stubs, quotes, and de-dupeing */
folders Q*
local years=ustrregexra(`"`=ustrregexra(`"`r(folders)'"',"Q[0-9]","")'"',`"""',"")
local years: list uniq years
foreach y of local years {
folders Q?`y'
foreach d in `r(folders)' {
cd "`d'"
fs filename*
foreach f in `r(files)' {
ls `f'
}
cd ..
}
}
回答2:
Stata has a set of extended functions for macros. See help extended_fcn
as a reference. One of these extended functions helps you grab names of folders and files.
To get a list of folders stored in a local macro named folderList
, use
local folderList : dir "<PATH1>" dirs "Q*"
where
<PATH1>
is the path to the folder containing the folders of interest. You can similarly pull file names in a folder using
local fileList : dir "<PATH2>" files "filenameQ*"
Here is the basic idea using two foreach
loops:
* get the list of folders
local path1 <PATH1>
local folderList : dir "`path1'" dirs "Q*"
* loop through folders
foreach folder of local folderList {
* get list of files
local fileList : dir "`path1'/`folder'" files "filenameQ*"
* loop through files
foreach file of local fileList {
* do stuff to file
use `file'
** do more stuff
}
}
I removed the cd
part as it is often preferable to keep the same working directory in order to specify the same output paths regardless of the location of the current file of interest.
来源:https://stackoverflow.com/questions/37845840/parsing-through-all-folders-in-a-directory