Triad sou.

実行ディレクトリを取得するマクロ

SASスクリプトをバッチ実行したときや、実行元のSASスクリプトファイルがあるディレクトリにファイル出力したり、グラフ出力したりするために作った物です。
多分2006年頃に作ったものですが、書く事もなかったので挙げなおしました。


マクロ本体

%macro setexecpath;
  %let execpath = %sysfunc(getoption(sysin));
  %if %length(&execpath) = 0 %then
    %let execpath = %sysget(sas_execfilepath);
  data _null_;
    count = 0;
    do i = length("&execpath") to 1 by -1;
      if substr("&execpath", i, 1) = '\' & count = 0 then do;
        call symput('Path', substr("&execpath", 1, i));
        count = 1; j = i;
      end;
      else if substr("&execpath", i, 1) = '\' & count = 1 then do;
        call symput('Dir', substr("&execpath", i + 1, j - i - 1));
        stop;
      end;
      else do;
        call symput('Dir', 'file');
      end;
    end;
  run;
%mend setexecpath;

%sysfunc(getoption(sysin))や%sysget(sas_execfilepath)で実行パスを取得します。
そして、"\" が見つかるまで1文字ずつ後ろから削っているだけです。
文字列判定の仕方から恐らくWindowsでしか動かないと思います。OS判定と処理変更で対応できるとは思いますが、UNIXユーザならこんなマクロは必要無いと思うので・・・

%setexecpath;

を実行すると、マクロ変数&Path.にSASスクリプトの実行パスが格納されます。


例えば、"C:/TEMP/hoge.sas"にマクロ本体を含めて以下の内容を記述して実行すると

%setexecpath;
data _null_;
  %let _EFIERR_ = 0; /* set the ERROR detection macro variable */
  %let _EFIREC_ = 0; /* clear export record count macro variable */
  file "&Path.\hoge.csv" delimiter=',' dsd dropover lrecl=32767;
  format x best12.;
  x = rand('Uniform');
  if _n_ = 1 then put 'x'; /* write column names */
  do;
    EFIOUT + 1;
    put x;
  end;
  if _ERROR_ then call symputx('_EFIERR_',1);  /* set ERROR detection macro variable */
  if EFIEOD then call symputx('_EFIREC_',EFIOUT);
run;

"C:/TEMP/hoge.csv"を出力する。
もちろん実行ディレクトリが変わると設定する必要なしに自動的に取得してくれる。


ここで公開しているSASスクリプトのいくつかには埋め込んであったかもしれません。