BookmarkSubscribeRSS Feed
mporras
Calcite | Level 5
Hi,

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
datafile=dr;
DBMS=TAB Replace;
getnames=yes;
datarow=2;
run;
%end;
%let rc=%sysfunc(dclose(&did));
%mend basic1; Message was edited by: mporras
2 REPLIES 2
andreas_lds
Jade | Level 19
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.
deleted_user
Not applicable
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 ;
&sysindex
%mend sysindex ;[/pre]It provides a macro wrapper around &sysindex.

PeterC

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 1214 views
  • 2 likes
  • 3 in conversation