I need to create a text file that includes text strings concatenated with field values from SAS datasets.
For example, here is a file:
My name is: John
Your name is: Jack
We live in: California
Here My name is: is a string
And John is a value of a field from a SAS dataset
Thanks to all who respond.
@chatur wrote:
Thanks so much. This is very helpful.
One follow up -
how would you write something like:
Child's name is "John"
Child's age is 12
(essentially, some data values need to be in quotes while others not)
To add quotes use the $QUOTE format.
put 'Child''s name is ' name :$quote.
/ 'Child''s age is ' age
;
A data step with PUT statements and a FILE statement to identify the output file name are one of the basic tools.
For example:
data _null_; set sashelp.class; file "c:\foldername\textfilename.txt"; put "Child's name is " name; put "Child's gender is " sex; put "Child's age is " age; run;
You can test the output but using FILE PRINT; instead of an actual file name it the output will be directed to your Results window.
There are options to control which column values appear such as @n where n is as column number, or + n to add n print positions to the output.
Caution: text written this way will seldom align vertically unless you use a fixed width font such as Courier to view the file.
To add quotes around the child's name, modify this statement:
put "Child's name is " name;
Within a set of quotes, repeating the quote gets printed as a quote. Yes, it sounds confusing, but it's easy once you try it:
put "Child's name is """ name +(-1) '"';
With three quotes in a row ("""), the first two printed as a quote. The third one ends the string.
The PUT statements leaves a blank after printing an unformatted variable (NAME). So +(-1) moves the pointer back a space allowing the PUT statement to overwrite that blank. Then '"' replaces the blank with a double quote.
@chatur wrote:
Thanks so much. This is very helpful.
One follow up -
how would you write something like:
Child's name is "John"
Child's age is 12
(essentially, some data values need to be in quotes while others not)
To add quotes use the $QUOTE format.
put 'Child''s name is ' name :$quote.
/ 'Child''s age is ' age
;
thanks. i will check it out.
Available on demand!
Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.
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.