从文件名设置变量以从目录读取所有文件 [英] Set a Variable from a filename to read all the files from a directory
问题描述
我想在SAS中使用文件名设置一个新变量.我在一个文件夹中有一堆txt文件,我有一个宏来读取我的所有文本文件,与此同时我想创建另一个变量来读取所有文件名.
I want to set a new variable with filename in SAS. I have a bunch of txt files in a folder, I have a macro that reads all my text files, along with this I want to create another variable where it reads all the filenames.
我试图做的事情与之前在这里提出的问题非常相似
what I am trying to do is very similar to the question asked here before
,这里提供的解决方案对我有用,但是它仅读取我的文件之一.我如何在宏中使用它,甚至单独使用它来输入我的所有文件名.
and the solution offered here works for me, except it only reads only one of my file. How can I use this in a macro or even by its own to input all my filenames.
reg1=prxparse("/\\(\w+\.csv)/");
if prxmatch(reg1, filename) then filename=prxposn(reg1,1,filename);
我要输入所有我的文本文件名称以及该文本文件具有的其他变量. 例如:
what I want is to input all my text file names along with the other variables the text files has. Eg:
filename var1 var2 var3
text1 xxx xxx xxx
text2 yyy yyy yyy
我还尝试了链接中提供的第二种解决方案.我正在使用SAS EG,但不允许我使用管道符号.对不起,如果我的问题太基础了.我是使用Perl表达式的新手.
I have also tried the second solution offered in the link. I am using SAS EG and it's not allowing me to use pipe symbol. Sorry if my question is too basic. I am new to using perl expressions.
推荐答案
仅一行,很难解释为什么该代码对您不起作用.
With only one line it's hard to explain why that code didn't work for you.
这是我的解决方案-没有正则表达式或宏.
Here's my solution - no regex or macro.
data import_all;
*make sure variables to store file name are long enough;
length filename txt_file_name $256;
*keep file name from record to record;
retain txt_file_name;
*Use wildcard in input;
infile "Path\*.txt" eov=eov filename=filename truncover;
*Input first record and hold line;
input@;
*Check if this is the first record or the first record in a new file;
*If it is, replace the filename with the new file name and move to next line;
if _n_ eq 1 or eov then do;
txt_file_name = scan(filename, -1, "\");
eov=0;
end;
*Otherwise go to the import step and read the files;
else input
*Place input code here;
;
run;
这篇关于从文件名设置变量以从目录读取所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!