How to read the contents of a file into a SAS macro variable

This post was kindly contributed by The SAS Dummy - go there to comment and to read the full post.

I’ve been working on a SAS program that can add content to the SAS Support Communities (more on that in a future post). Despite my 20+ years of SAS experience, there are a lot of SAS programming tricks that I don’t know. Or that I use so infrequently that I always need to remind myself how to accomplish them.

Here’s one. I needed to read the contents of an external text file into a SAS macro variable, so that I could then use that value (a very long text string) as part of an API call. In searching for a technique that would work for me, I came across a similar question on SAS Support Communities — one that had been solved by our resident SASJedi, Mark Jordan. Perfect!

Here’s the solution that worked for me:

FILENAME msghtml "path-to-text-file" ;
data _null_;
   length text $32767;
   retain text '';
   infile msghtml flowover dlmstr='//' end=last;
   input;
   text=cats(text,_infile_);
   if last then call symput('MSGBODY',text);
run;

The RETAIN statement allows me to build up the “text” variable as the DATA step processes multiple lines. The END=last on the INFILE statement sets a flag when we hit end-of-file, so I know that we’re done and I can CALL SYMPUT the macro value. The FLOWOVER option tells the INPUT statement to keep reading even if no input values are found in the current record. (FLOWOVER is the default behavior, so the option probably isn’t needed here.) DLMSTR allows you to specify a multichar delimiter string that’s different than the default delimiter (a space character). We’re using the CATS function to concatenate a trimmed version of the input buffer (_INFILE_) to the RETAINed “text” variable.

For my project I needed to URL-encode the text value for use in an HTTP-based REST API. So for me, the last line is really:

if last then call symput('MSGBODY',urlencode(trim(text)));

The SAS Support Communities has been a big help to me during this project — a project that is designed to improve the communities even more. It’s a virtuous cycle! I hope that this helps some of you out there, too.

tags: macro programming, SAS Communities, SAS programming

The post How to read the contents of a file into a SAS macro variable appeared first on The SAS Dummy.

This post was kindly contributed by The SAS Dummy - go there to comment and to read the full post.