You can use the code in the Full Code section to replace a simple string in all files contained within a given directory.
This sample code replaces the string XYZ with ZYX in all files. You can modify the macro for more complex strings.
Since you cannot write back to the file that you are currently reading, this sample creates a new file for each file that is read. You can modify the macro to delete all original files and rename the new files with their original names.
This sample code is written for Microsoft Windows. So if you run on a different operating system, you must modify the path structure within the code.
See comments within the code for more details.
Full Code
Modify the sample code below to replace a string in all files contained within a given directory.
%macro drive(dir,ext,from,to);
%local filrf rc did memcnt name i;
/* Assigns a fileref to the directory and opens the directory. */
%let rc=%sysfunc(filename(filrf,&dir));
%let did=%sysfunc(dopen(&filrf));
/* Makes sure the directory can be opened. */
%if &did eq 0 %then %do;
%put Directory &dir cannot be open or does not exist;
%return;
%end;
/* Loops through the entire directory. */
%do i = 1 %to %sysfunc(dnum(&did));
/* Retrieves the name of each file. */
%let name=%qsysfunc(dread(&did,&i));
/* Checks to see whether the extension matches the parameter value. */
/* If the condition is true, prints the full name to the log and makes modifications to the file. */
%if %qupcase(%qscan(&name,-1,.)) = %upcase(&ext) %then %do;
%put &dir\&name;
data _null_;
infile "&dir\&name";
file "&dir\%sysfunc(tranwrd(&name,.txt,1.txt))";
input @;
_infile_=transtrn(_infile_,"&from","&to");
put _infile_;
run;
%end;
/* If directory name, calls the macro again. */
%else %if %qscan(&name,2,.) = %then %do;
%drive(&dir\%unquote(&name),&ext)
%end;
%end;
/* Closes the directory and clears the fileref. */
%let rc=%sysfunc(dclose(&did));
%let rc=%sysfunc(filename(filrf));
%mend drive;
/* First parameter is the directory of where your files are stored. */
/* Second parameter is the extension that you are looking for. */
/* Third parameter is the string that you are searching for. */
/* Fourth parameter is the string that you are replacing it with. */
/* This example changes XYZ to ZYX in all .txt files. */
%drive(c:\change,txt,XYZ,ZYX)