0

I need to save an output file under a filename based on the path of the current directory. For example, I have the current directory and the initial dataset defined as follows:

// current directory
cd "C:\Users\Raw data AA SYS BEST" 
// the initial master dataset in "analysis" subfolder
use "analysis\master.dta" , clear

I need the output file to be saved under the name "analysis\output_AA_SYS_BEST.dta" in the same "analysis" subfolder.

There were two problems that I have encountered:

(1) how to extract the portion of the directory name. I managed to find some useful information as to how to use the substr() function to extract the portion of the list of filenames stored within the same directory (http://www.ats.ucla.edu/stat/stata/faq/append_many_files.htm), but not the directory itself.

(2) I have tried a simpler way of defining a local macro upfront and then concatenating it with the file name, but it did not work, presumably because of the syntax errors:

 local x "AA SYS BEST"
 save "analysis\test"_"`x'"_".dta"
Nick Cox
  • 35,529
  • 6
  • 31
  • 47
user2700264
  • 177
  • 1
  • 4
  • 17
  • 1
    For (1), I think `filelist` (from SSC) could be useful. See an answer from http://stackoverflow.com/q/35558697/2077064 that might help. – Roberto Ferrer Mar 03 '16 at 18:59
  • Roberto, thanks for this, it works indeed if I assign `local x=substr(dirname,10,10)`. Do you know it is also possible to define `filelist, directory("C:\...")` without actually having to enter the entire path again? Something like `filelist, directory(cd)`? – user2700264 Mar 04 '16 at 13:42
  • Put the path in a local macro, and use that thereafter. – Roberto Ferrer Mar 04 '16 at 15:24

1 Answers1

1

On (1) I am not clear what your problem is, and see no code example.

On (2) this should work:

local x "AA SYS BEST"
save "analysis\test_`x'_.dta"

But watch out if backslashes and local macro names abut. Use forward slashes instead. So this should not work

local x "AA SYS BEST"
save "analysis\`x'_.dta"

but this should work, even in Windows,

local x "AA SYS BEST"
save "analysis/`x'_.dta"

For more on backslashes, see 18.3.1 http://www.stata.com/manuals14/u18.pdf or http://www.stata-journal.com/sjpdf.html?articlenum=pr0042

Nick Cox
  • 35,529
  • 6
  • 31
  • 47