I want to scan for files in one shared folder and if file name contains 5601, 6010 or 6020 then I want to rename the file name by adding a string 'copied' before .CSV (e.g. IFR_RIS_1_ACC_5601_1_20200118_copied.csv ). Just don't do anything if filename don't have 5601, 6010 or 6020
File name looks like,
IFR_RIS_1_ACC_5601_1_20200118.csv
Do you have the code that scans the files in the shared folder in place?
Please show the code for scanning, which is necessary for us to help you do the file renames. And (just in case the code doesn't make it evident) what is the operating system that is being used to store the files?
By
I can't use OS commands though.
I presume you mean you can't use the X "command" statement in SAS.
%macro t2(folder=);
data _null_;
rc=filename("mydir","&folder");
did=dopen("mydir");
mem_count=dnum(did);
length fname new_name $64;
do i=1 to mem_count;
fname=dread(did,i);
copy='no ';
new_name=' ';
if countw(fname,'.')>1 and upcase(scan(fname,-1,'.'))='CSV' then do;
if find(fname,'5601') then copy='yes'; else
if find(fname,'6010') then copy='yes'; else
if find(fname,'6020') then copy='yes';
if copy='yes' then do;
new_name=tranwrd(fname,".csv","_opened.csv");
rename_rc=rename (cats("&path,/",fname),cats("&path,/",new_name),"FILE");
end;
end;
end;
rc_close=dclose(did);
run;
%mend;
options mprint;
%t2(folder=c:\temp);
> I want to move the files to the target folder
There is no SAS function to move files under Windows. You need to use fcopy() then fdelete().
> I want to rename the file name by adding a string 'copied'
You can add something like this to the data step that processes the file names:
if index(FILENAME,'5601')
| index(FILENAME,'5610')
| index(FILENAME,'5620')
then RC=rename(FILENAME, scan(FILENAME,1,'.') || '_copied.csv', 'file' );
if index(FILENAME,'5601') | index(FILENAME,'5610') | index(FILENAME,'5620') then RC=rename(FILENAME, scan(FILENAME,1,'.') || '_copied.csv', 'file' );
This can be shortened to
if prxmatch('/5601|5610|5620/',FILENAME) then RC=rename(FILENAME, scan(FILENAME,1,'.') || '_copied.csv', 'file' );
@David_Billa wrote:
Thanks. I got it. But one more question.
If the file name has 'copied' after moving that file to the target folder I
want to rename the filename by removing the string '_copied' from the file
name. How to tackle this with substr and rename function?
Your welcome, but I have one more comment.
I write code like this to help understanding. I try to stop when I am merely being asked to do someone else's job.
The code I provided shows the principle of how to do the new task. Use it and learn. It can be like swimming the Hellespont - difficult but worth it.
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.