Search code examples
sasconcatenationsas-macro

Concatenate quoted macro variables


I'm just trying to concatenate two quoted macro variables but there doesn't seem to be an easy way.

Say we have:

%LET VAR1="This is not the greatest song in the world";
%LET VAR2="this is just a tribute.";

%LET TRIBUTE=%SYSFUNC(CATX(%STR( ),&VAR1,&VAR2));
%PUT &TRIBUTE;

I actually want:

  "This is not the greatest song in the world this is just a tribute."

But the above code actually yields:

"This is not the greatest song in the world"  "this is just a tribute."

So I try putting %QUOTE(),%BQUOTE,etc. around &VAR1 and %VAR2 in hopes of unmasking the quotes but I get the same result.

The only thing that works for me is:

 %LET TRIBUTE="%SUBSTR(&VAR1.,2,%LENGTH(&VAR1.)-2) %SUBSTR(&VAR2.,2,%LENGTH(&VAR2.)-2)"; 

But this is ugly and can get lengthy really fast. Is there not a better way to do this ?


Solution

  • You can use COMPRESS to do this.

    %LET VAR1="This is not the greatest song in the world";
    %LET VAR2="this is just a tribute.";
    
    
    %let VAR3=%sysfunc(compress(&VAR1,%str(%")));
    %put &=var1 &=var3;
    

    It's a bit tricky to remove quotes, but it works.

    You could also do this in a FCMP function, or a function-style macro; here is one example.

    %macro unquote_string(string=);
    %sysfunc(compress(&string.,%str(%'%")))
    %mend unquote_string;
    
    %let VAR3="%unquote_string(string=&var1.) %unquote_string(string=&var2.)";
    %put &=var3.;
    

    Note you shouldn't use CAT functions to concatenate macro variables. They're just text, so typing one after the other automatically concatenates them.

    However, the real answer to your question of 'Is there a better way', is to not store the quotes in the macro variable. Most of the time you should store the macro variable w/o quotes and use it within quotes when needed. SAS Macros do not respect quotes as anything special - they're just a character in a string - so they don't have a specific tool for dealing with this.