Hi,
I have a bunch of folders that all have a dataset with the same name in them.
folder1, folder2, folder3, folder4. all contain mydata.
i was wondering if it was possible to do a DO LOOP over a list of these folder names and run an extraction macro of these datasets.
So far all the things i've seen online are for looping over files within a folder and not looping over folders/libraries.
any help would be greatly appreciated thanks.
Do you know the names of the folders in advance, or does your code have to figure this out?
I know the folders in advance.
So you read the known names of the folders into a SAS data set somehow (for example, by reading a text file of those names, one name on each row). Then you use CALL EXECUTE to effectively call the macro using each folder name. Something like this (you will have to replace the macro with your actual extraction macro)
data _null_;
set list_of_folder_names;
full_path_name=cats(folder_name,'\',file_name);
call execute('%nrstr(%extract('||full_path_name||'))');
run;
Without more details, I can't be more specific.
Yes, it is possible.
Put them in a data set and then use something like this:
https://github.com/statgeek/SAS-Tutorials/blob/master/Turning%20a%20program%20into%20a%20macro.md
Are you familiar with the macro language? Are you looking at examples of macros that use %DO loops to loop over files?
If so, a key point is that a macro %DO loop that iterates over a list does not know if the list is a list of files, or directories, or elephants. There are no 'objects' in the macro language. Everything is just text. So the list is literally just a list of words.
If you have an example you understand which is using the macro language to loop over a list of files, you could try revising it to loop over a list of libraries. Once you have a good understanding of macro looping, then you can loop over anything, because every list is just a list of words. Here's one way to loop over a space-delimited list:
%macro try(list=) ;
%local i item ;
%do i=1 %to %sysfunc(countw(&list,%str( ))) ;
%let item=%scan(&list,&i,%str( )) ;
%put item &i: &item ;
/**
*here you could write any SAS code to execute for each item ;
libname mylib "c:\&item" ;
data want ;
set mylib.mydata ;
run ;
proc append base=wantall data=want ;
run ;
*this could also be a macro call e.g. : ;
%extract(folder=&item)
**/
%end ;
%mend try ;
%try(list=aaa bbb ccc)
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!
Check out this tutorial series to learn how to build your own steps in SAS Studio.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.