SAS获取某目录下所有指定类型的文件名称

QQ今天看到一个群友(QQ群:144839730,加群请扫上面的二维码)提的一个问题:SAS中如何简单地获取某一目录下所有指定类型的文件名称并赋值为宏变量?用常规的方法可能要20多行代码,如果用FILENAME PIPE只需要9行代码就可以轻松解决,语法如下:

FILENAME fileref PIPE 'UNIX-command' ;
fileref

is the name by which you reference the pipe from SAS.

PIPE

identifies the device-type as a UNIX pipe.

'UNIX-command'

is the name of a UNIX command, executable program, or shell script to which you want to route output or from which you want to read input. The commands must be enclosed in either double or single quotation marks.

以获取程序所在目录下所有TXT文件名为例,实现代码如下:

filename filelst pipe "ls ./*.txt | sed -e 's#.*/##; s#\..*$##' | paste -sd '|' -";

data _null_;
    infile filelst lrecl=32767;
    input;
    call symputx('filelst', _INFILE_, 'L');
run;

filename filelst clear;

简单介绍一下上面的UNIX命令:其中的s#.*/##是用来去掉目录;s#\..*$##是用来去掉文件后缀;命令paste,顾名思义就是将几个文件连接起来;选项-s的作用是将每个文件作为一个处理单元;选项-d的作用是用来设定间隔符。连接功能也可以用AWK来实现,即:

filename filelst pipe "ls ./*.txt | sed -e 's#.*/##; s#\..*$##' | awk 'ORS=""|""'";

不过这个命令有一个小问题,就是在最后会多出一个间隔符,需要在后续的DATA步中处理一下。

曾宪华 /
本文采用 署名-非商业性使用-相同方式共享 3.0许可协议 属于 程序人生 分类, 被贴了 AWK FILENAME PIPE sed 书签

上一篇 Linux命令批量修改文件名字及内容
下一篇 SAS获取某目录下某种类型文件最后修改时间