Saturday, June 30, 2012

Search all of the data in a directory for a variable

* This command looks in a directory through all of the data files for a text match in either the name of the variables or the description of the variables.

* Specify where to look.  I have all of my the data files from Jeffrey Wooldridge's Introductory Econometrics book in one directory.
local targ_dir = "A:/Wooldridge/"

* What to look for
local lookforwhat "computer" /* I know that one of Jeff's examples uses computers and coupons */

dir "`targ_dir'*.dta"

* Creates a list of data files in the directory and stores them in the `file_list' local
local file_list : dir "`targ_dir'" files "*.dta"

* Saves your current data

preserve

* Loops through all of the files in the file list
foreach v in `file_list' {
  * Tells the user what files is being openned
  di as input "Opening: `v'"

  * Opens the data file
  use "`targ_dir'\`v'", clear

  * Looks within the data file for the text match
  lookfor `lookforwhat'

  * Saves the match to `found_result' if a variable is found
  local found_result = r(varlist)

  * If a variable is found then it displays a message though of course the lookfor command also displays useful results
  if length("`found_result'")>1 di  _newline "`lookforwhat' found in file `v'" _newline

}


* Restores the user's data to the previous state.
restore

No comments:

Post a Comment