Copy .sas files (program files) with SAS

The code below copies all the SAS-programs (*.sas) files in a directory to another directory. This solution should be used if you don’t want to use an OS-command that copies the files. Using an OS-command is a lot easier and doesn’t require as much code. But of course depends on the OS your running on. This solution is OS independent.

%let SourcePath = C:\test\source;
%let DestinationPath = C:\test\destination;

/*
Reads the .sas files in &location.
*/
%macro GetFilenames(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;

%GetFilenames(&SourcePath.);

/* We only want SAS-files and not SAS-datasets. */
data filenames;
 set filenames;
 if index(memname, '.sas') eq 0 or index(memname, '.sas7bdat') eq 1 then delete;
run;

%let Delimitor = ¤;

proc sql noprint;
 select memname into :Files separated by "&Delimitor"
 from FileNames;
quit;

%put Files to copy: &Files;

%macro CopySASFiles;
 %let NumberOfFiles = %sysfunc(countw(&Files., &Delimitor.));
 %put Number of files: &NumberOfFiles.;

 %do J=1 %to &NumberOfFiles.;
  %let File = %scan(&Files., &J, &Delimitor.);
  %put Copying SAS-program: &File.;

  data _null_;
   infile "&SourcePath.\&File."  lrecl=32767;
   file "&DestinationPath.\&File.";
   input;
   put _infile_;
  run;
 %end;
%mend;
%CopySASFiles;

 

Writing a SAS-program in SAS

The code below will let you write a SAS-program in SAS.

/* This dummy macro-variable will be used later as input for the SAS program. */
%let HelloWorld = Hello world;
data _null_;
file SASProgram;
put ‘%let Hello='” &HelloWorld. “‘;’;
put ‘%put &Hello;’;
put ‘run;’;
run;

filename cdrive “C:\SASPrograms”;

data _null_;
infile SASProgram;
file cdrive(HelloWorld.sas);
input;
put _infile_;
run;
filename cdrive clear;

You now have a SAS-program called ‘HelloWorld.sas‘ in the folder ‘C:\SASPrograms\‘.
The program will look like this.

%let Hello= Hello World;
%put &Hello;
run;

And it will write ‘Hello World‘ to the log in SAS.

Getting path for the SAS-program being executed

/* Gets path for the SAS-program being executed */

%macro GetSASProgramPath;
%qsubstr(%sysget(SAS_EXECFILEPATH),1,%length(%sysget(SAS_EXECFILEPATH))-%length(%sysget(SAS_EXECFILEname)));
%mend;

%let SASProgramPath = %GetSASProgramPath;

This will only work on Windows.

In batchmode you can get the programname with the code below. This will  work in eg an AIX environment.

%let ProgramName = %sysfunc(getoption(sysin));
%put &ProgramName;