问题
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
SAS set a variable from a filename
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
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.
回答1:
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;
来源:https://stackoverflow.com/questions/31844986/set-a-variable-from-a-filename-to-read-all-the-files-from-a-directory