### SAS FAQ: How do I write out a fixed-format file in SAS?

If you wish to write a fixed-format file out of SAS, this can be easily be done with the filename and put commands. We can look at a few examples of how you can write different fixed formats that you'd wish for in your output file.  First, we can create a dataset.  We will use a portion of the hsb2 data.


data hsb2;
input  id female race ses prog
sub1 sub2 sub3 sub4 sub5;
datalines;
70 0 4 1 1 57 52 41 47 57
121 1 4 2 3 68 59 53 63 61
86 0 4 3 1 44 33 54 58 31
141 0 4 3 3 63 44 47 53 56
172 0 4 2 2 47 52 57 53 61
113 1 4 2 2 44 52 51 63 61
50 0 3 2 1 50 59 42 53 61
11 0 1 2 2 34 46 45 39 36
84 0 4 2 1 63 57 54 51 63
48 1 3 2 2 57 55 52 50 51
75 1 4 2 3 60 46 51 53 61
60 1 4 2 2 57 65 51 63 61
95 0 4 3 2 73 60 71 61 71
104 0 4 3 2 54 63 57 55 46
38 0 3 1 2 45 57 50 31 56
115 0 4 1 1 42 49 43 50 56
76 0 4 3 2 47 52 51 50 56
195 0 4 2 1 57 57 60 56 52
;
run;


If we wish to create a file in which we specify the column placement at which each variable starts, we can do this by first defining the fixed-format file we wish to create and then writing data to it in a data step.  We set the dataset with the variables we wish to write out, indicate the file to which we will write them out in the file statement, and then specify each variables location with @ in the put statement.  This is done in the following code:


filename out "C:\hsb2.txt";

data _null_; set hsb2;
file out;
put @1 id @4 female @5 race @6 ses @7 prog @8 sub1 @10 sub2 @12 sub3 @13 sub4 @15 sub5;
run;


We can use the put statement to add in delimiters. In the example below, we separate each variable with a pipe ("|").


filename out_pipe  "C:\hsb2_pipedelim.txt";

data _null_; set hsb2;
file out_pipe;
put "|" id "|" female "|" race "|" ses "|" prog "|" sub1 "|" sub2 "|" sub3 "|" sub4 "|" sub5;
run;

If we have a set of enumerated variables, like sub1-sub5 in the hsb2 dataset, we can use a macro to write out these variables. In the example below, we again create a pipe-delimited file, but this time, we use use a loop to go through the subject variables.


filename out_mac  "C:\hsb2_macro.txt";

%macro makeff();
data _null_; set hsb2;
file out_mac;
put id "|" female "|" race "|" ses "|" prog
%do i = 1 %to 5;
"|" sub&i
%end;
;
run;
%mend;

%makeff();

The content of this web site should not be construed as an endorsement of any particular web site, book, or software product by the University of California.