I avoided this question the first time as I
couldn't instantly see what was going on,
but it yields to a little analysis.
You have to see this the way that Stata sees this;
then everything is crystal clear!
The result of your
local files : dir . files "*.dta"
will be a local macro containing
"france 2002.dta" "germany 2001.dta" "united states 2002.dta"
You can only see this properly with compound double quotes:
. di `"`files'"'
The rationale here is clear: as your OS allows filenames
to contain spaces, something which you are exploiting,
the Stata command must bind those filenames in double
quotes when it produces the local macro. This incidentally is why your
. display `files'
worked without an error message. Stata just stripped
the double quotes, and displayed the rest. Usually
when a local macro contains an arbitrary string
there is a large chance of an error message, as
Stata tries to look for a variable or variables
with the appropriate names, or scalars, etc. Thus with
the auto data, or almost any other data, if I go
. local frog "frog"
. di `frog'
Stata interprets this as
. di frog
and looks in vain (usually) for a variable
called -frog-. If I go
. di "`frog'"
thereby insisting to Stata that the macro
is to be treated as a string, then all is
OK, except that if the macro contains " "
then I should go
. di `"`frog'"'
Now -- when you zap the string
united states 2002.dta
the result is
"france 2002.dta" "germany 2001.dta" ""
i.e. the last word of the macro, "words" being bound
here by " ", is an empty string, and Stata doesn't
like it. Note that the empty string is in fact being
displayed, as you pointed out.
In short, you have to remember that the macro here
_contains_ "", which serve as internal delimiters.
Nick
[email protected]
Friedrich Huebler
>
> Thank you Michael and Nick. I will have a look at -fs- but first I
> want to understand -subinstr-. I tried another way to strip "united
> states 2002.dta" from the file list. However, when I pass this macro
> to a loop I now get an error message because the macro "files2" still
> contains three items, the last of which appears to be a blank.
>
> . local files: dir . files "*.dta"
> . di `files'
> france 2002.dtagermany 2001.dtaunited states 2002.dta
> . local files2: subinstr local files "united states 2002.dta" ""
> . di `files2'
> france 2002.dtagermany 2001.dta
> . foreach file of local files2 {
> 2. di "`file'"
> 3. use "`file'", clear
> 4. }
> france 2002.dta
> germany 2001.dta
>
> invalid file specification
> r(198);
>
> Notice the blank line before "invalid file specification". If I
> switch the second and third lines of the -foreach- loop, the blank
> line does not appear.
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/