How can I add a underscore at the end of each macro variable?
For example, I have: %LET mvar= var1 var2 var2.. I want mvar to contain var1_ var2_ var2_
That is adding underscores in the MIDDLE of the VALUE of the macro variable.
If you know that the string only has one space between the words then you can use TRANWRD() function. You will have to use the %SYSFUNC() macro function to use TRANWRD() function in macro code.
%let mvar=%sysfunc(tranwrd(&mvar,%str( ),%str(_ )))_;
If you are worried it might have multiple spaces between the words then use COMPBL() first.
%let mvar=%sysfunc(tranwrd(%sysfunc(compbl(&mvar)),%str( ),%str(_ )))_;
Example
818 %LET mvar= var1 var2 var2 ; 819 820 %let mvar=%sysfunc(tranwrd(%sysfunc(compbl(&mvar)),%str( ),%str(_ )))_; 821 822 %put &=mvar; MVAR=var1_ var2_ var2_
%LET mvar= var1 var2 var2 ; %let mvar=%sysfunc(prxchange(s/(\w+)/$1_/,-1,&mvar)); %put &=mvar;
Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9.
Lock in the best rate now before the price increases on April 1.
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.