DATA Step, Macro, Functions and more

Multiple file saving from a directory

New Contributor
Posts: 3

Multiple file saving from a directory


I am using a macro to open multiple txt files from a directory but want to store them under a subsetname of the files. Once i assign the file name it can't store it because of the txt extension, how can i make it to store my the files? Could somebody please help me figure out what is wrong here?

This is the code;

macro basic1;
%let filrf=mydir;
%let rc=%sysfunc(filename(filrf,"F:\RESEARCH MELISSA\Short USA DATA\")); /* assign dir name */
%let did=%sysfunc(dopen(&filrf)); /* open directory */
%let lstname=; /* clear filename macro var */
%let memcount=%sysfunc(dnum(&did)); /* get # files in directory */
%if &memcount > 0 %then /* check for blank directory */
%do i=1 %to &memcount; /* start loop for files */
%let lstname=%sysfunc(dread(&did,&i)); /* get file name to process */
%let lstname2=%sysfunc(substr("&lstname",24,7));
filename dr "F:\RESEARCH MELISSA\Short USA DATA\&lstname"; /* assign file name */
proc import out=&LSTNAME2
DBMS=TAB Replace;
%let rc=%sysfunc(dclose(&did));
%mend basic1; Message was edited by: mporras
Super Contributor
Posts: 264

Re: Multiple file saving from a directory

You can use the %scan-function to extract the part before .txt, afterwards it may be necessary to remove any other char not allowed in dataset names. The translate function could be useful for that job.
Posts: 0

Re: Multiple file saving from a directory

to test the validity of a string for use as a name (either data set name or variable name) use the function NVALID()
For example, replace unsuitable name with a generated name like[pre] %if not %sysfunc( nValid( &lstName2 )) %then %do ;
%let newName = gen%SYSINDEX ;
%put lstname2 = %quote(&lstName2) unsuitable. Using &newName ;
%let lstname2 = &newName ;
%end ;[/pre]

There I used %sysindex. &SYSINDEX delivers a constant each time the macro in which it is present is called. However I want an increasing counter. So I create %SYSINDEX because it is not automatically available, and is very convenient and simple to create.[pre]%macro sysindex ;
%mend sysindex ;[/pre]It provides a macro wrapper around &sysindex.

Ask a Question
Discussion stats
  • 2 replies
  • 3 in conversation