如何编写sas代码来读取不同文件夹中的文件?

时间:2014-12-05 00:14:04

标签: sas sas-macro

我想知道是否可以写一个宏来读取文件 在不同的文件夹中。

例如,我有100个文件夹,在每个文件夹中, 它有另一个文件夹,在子文件夹中它可能包含一个txt文件,我 想用SAS阅读。可以创建新文件夹以包含新文件。

Folder1 folder2文件

A1 aa1 file1

A2 aa2(nofile)

...... .. ...

A100 aa100 file100

Folder2在folder1中,文件存储在folder2中。

由于

陈旭

1 个答案:

答案 0 :(得分:1)

以下宏可能会完成这项工作;

  %macro procesFilesInRoot(rootFolder,fileExt,procesMacro);  
        %put "dir ""%unquote(&rootFolder)"" /s /b";

      filename pipeTree pipe "dir ""%unquote(&rootFolder)"" /s /b" lrecl=32767; 
      data fullNames;
          infile pipeTree truncover;
          input fullName $char1000.;
              ext = upcase(scan(fullName,countw(fullName, '.'), '.'));
          if ext = "%upcase(&fileExt)";
      run;
      filename pipeTree clear; 

        title 'files found';
        proc print;
        run; 

      proc sql noprint;
          select count(*) into :nrFiles from fullNames;
          %let nrFiles = &nrFiles; /** to strip the leading blanks **/
              %if &nrFiles %then %do;
              select fullName into :fullName1-:fullName&nrfiles from fullNames;
              %end;
      quit;

      %do fileNr = 1 %to &nrFiles.;
          %&procesMacro(&&fullName&fileNr);
      %end;
  %mend;

在使用它之前,您需要编写一个处理单个输入文件的宏;

  %macro import1file(fullName);
      %let fileName = %scan(&fullName,%sysfunc(countw(&fullName, '\')), '\');
      %let fileExt = %scan(&fileName,%sysfunc(countw(&fullName, '.')), '.');
      %let dataName = %substr(&fileName,1, %length(&fileName)-%length(&fileExt)-1);

      proc import datafile = "&fullName" out=&dataName;
      run;
  %mend;

然后您可以按如下方式使用;

  %procesFilesInRoot(D:\Horsten,txt,import1file);