2
votes

I would like to iterate through files in a particular folder, and extract substrings of their files names. Is there an easy way to do this?

lib dir '.../folder';
#iterate through all files of dir and extract first five letters of file name;
#open files and do some processesing, aka data steps proc steps;
1
What have you tried so far? This is a very common question and a search on SO, or on google will yield many results.Robert Penridge

1 Answers

3
votes

Firstly, I'd point out that "dir" appears to be a misspelt libref, not a folder. If you are looking for files in a folder, you can use:

   %macro get_filenames(location);
    filename _dir_ "%bquote(&location.)";
    data filenames(keep=fname);
      handle=dopen( '_dir_' );
      if handle > 0 then do;
        count=dnum(handle);
        do i=1 to count;
          fname=subpad(dread(handle,i),1,5);/* extract first five letters */
          output filenames;
        end;
      end;
      rc=dclose(handle);
    run;
    filename _dir_ clear;
    %mend;

%get_filenames("c:\temp\");

If you are looking for datasets in a library, you can use:

proc sql;
create table datasets as
  select substr(memname,1,5) as dataset
  from dictionary.tables
  where libname='LIB'; /* must be uppercase */

either approach will produce a dataset of 'files' which can be subsequently 'stepped through'..