Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SAS Macro to pipe a list of filenames from a Windows directory

I am trying to amend the macro below to accept a macro parameter as the 'location' argument for a dir command. However I cannot get it to resolve correctly due to the nested quotes issue. Using %str(%') does not work, neither do quoting functions for some reason.

The macro will work fine when the filepath has no spaces (eg C:\temp\withnospace) as the middle quotes aren't needed. However I need this macro to work for filepaths with spaces (eg 'C:\temp\with space\').

Please help!

%macro get_filenames(location)
   filename pipedir pipe   "dir &location. /b " lrecl=32767;
   data filenames;
     infile pipedir truncover;
     input line $char1000.;
   run;
%mend;

%get_filenames(C:\temp\)              /* works */
%get_filenames('C:\temp\with space')  /* doesnt work */
like image 535
Allan Bowe Avatar asked Sep 11 '09 07:09

Allan Bowe


2 Answers

Here's another way of achieving the same result without needing to use a PIPE.

%macro get_filenames(location);
filename _dir_ "%bquote(&location.)";
data filenames(keep=memname);
  handle=dopen( '_dir_' );
  if handle > 0 then do;
    count=dnum(handle);
    do i=1 to count;
      memname=dread(handle,i);
      output filenames;
    end;
  end;
  rc=dclose(handle);
run;
filename _dir_ clear;
%mend;

%get_filenames(C:\temp\);           
%get_filenames(C:\temp\with space);
%get_filenames(%bquote(C:\temp\with'singlequote));
like image 53
cmjohns Avatar answered Nov 13 '22 09:11

cmjohns


Make the following several changes and your code will work.

%macro get_filenames(location);  %*--(1)--*;
   filename pipedir pipe "dir ""%unquote(&location)"" /b" lrecl=32767; %*--(2)--*;
   data filenames;
     infile pipedir truncover;
     input filename $char1000.;
     put filename=;
   run;
   filename pipedir clear;  %*--(3)--*;
%mend;

%get_filenames(d:\)          
%get_filenames(d:\your dir)  %*--(4)--*;

(1) End the %macro statement with a semi-colon;

(2) Surround the macro variable resolution with doubled-up double quotes and %unquote;

(3) Release the file handle by clearing it; and

(4) Don't single quote your input parameter. macro quote instead, if necessary.

like image 6
Chang Chung Avatar answered Nov 13 '22 11:11

Chang Chung