/*
Name: modify_a_file.sas
Description: This program is used to replace old string in a text file by new one
Input: path_name: file name and path
old_str: old string in the file need to be replaced
new_str: now string used to replace old one
case_sen: case_sen = Y or y - case sensitive
case_sen ne Y or y - not case sensitive
defcult value is Y.
Output: update file with repalcing old string by new string
Example:
%modify_file(path_name =
C:\zhu_test\test9\temp_XXX.sas,
old_str =
#FORM#,
new_str =
test);
%let str = %nrstr(%let);
%let str1 = %nrstr(%LET);
%modify_file(path_name =
C:\zhu_test\test9\temp_XXX.sas,
old_str =
&str.,
new_str =
&str1.);
History:
Date
Name
Comments
5/18/2005 Songlin Zhu created
*/
/* Modify a file with updated information */
%macro modify_file(path_name=, old_str=, new_str=, case_sen=Y);
/* Save information of an external file into a data set */
data temp_;
attrib obs_n length=$4;
attrib str length=$250;
infile "&path_name." lrecl=250 pad ;
input @1 str $char250.;
str = trim(str);
obs_n = put(_n_,z4.);
run;
%if "&old_str." ne "" %then
%do;
/* Find old string (last version number) and replaced it with new string */
%if %cmpres(&case_sen.) = Y or %cmpres(&case_sen.) = y %then
%do;
proc sql noprint;
update temp_
set str = tranwrd(str, "&old_str.", "&new_str.")
where (index(str, trim(left("&old_str."))) > 0)
;
quit;
%end;
%else
%do;
%put ----------------> &case_sen. &old_str. &new_str.;
%let temp_str = upcase(trim(left("&old_str.")));
%let pos_1 = index(upcase(str), &temp_str.);
%let len_1 = length(&temp_str.);
%let old_str1 = trim(left(substr(str, &pos_1., &len_1.)));
proc sql noprint;
update temp_
set str = tranwrd(str, &old_str1., "&new_str.")
where (index(upcase(str), upcase(trim(left("&old_str.")))) > 0)
;
quit;
%end;
/* Output updated information into an external file */
data _null;
set temp_;
str = trim( str );
length_of_line = length( str );
file "&path_name";
put str $varying250. length_of_line ;
run;
%end;
%else
%do;
%put Old string need to be given.;
%end;
%mend modify_file;
If you want to
replace a string containing SAS key words like "%let" and
"%include", you can't call the macro by assigning it to the macro
variable &old_str like follows:
%modify_file(path_name =
C:\zhu_test\test9\temp_XXX.sas,
old_str =
%let,
new_str = test);
What you need to do is using %nrstr function to mask this string
because it contains special character like % and &. The correct way
to call the macro is:
%modify_file(path_name =
C:\zhu_test\test9\temp_XXX.sas,
old_str =
%nrstr(%let),
new_str = test);
If you have any questions, feel free to send me feedback.
|