### Stata FAQ How can I output a formatted ASCII file?

Say that you want to output the data from Stata to a formatted ASCII file, that is, a file where variables are in specific columns and may be on different lines. To accomplish this we will use Stata file command in a do-file. Obviously, you will have to change the file name, variable names and column locations to suit your own needs.

To use the do-file, just copy the commands and save them as outform.do in the same directory as your data file.

capture file close temp
use http://www.ats.ucla.edu/stat/stata/notes/hsb2, clear
generate obs = _n

quietly count
local l = r(N)

file open temp using outtest.txt, write text replace

/* be sure to include all semi-colons */

#delimit ;

foreach i of numlist 1/l' {;
file write temp
_col(2)   %3.0f  (obs[i'])
_col(6)   %3.0f  (id[i'])
_col(10)  %1.0f  (female[i'])
_newline
_col(14)  %3.0f  (write[i'])
_col(18)  %3.0f  (math[i'])
_newline;
};

#delimit cr
file close temp
clear
Now that you have the do-file, you can run it with the do command, and you can view the results using the type command.
do outform

type outtest.txt
1  70 0
57.00 52 41
2 121 1
68.00 59 53
3  86 0
44.00 33 54
4 141 0
63.00 44 47
5 172 0
47.00 52 57
6 113 0
44.00 52 51
7  50 0
50.00 59 42
8  11 0
34.00 46 45
9  84 0
63.00 57 54
10  48 0
57.00 55 52
11  75 0
60.00 46 51
12  60 0
57.00 65 51
13  95 0
73.00 60 71
14 104 0
54.00 63 57
15  38 0
45.00 57 50
16 115 0
42.00 49 43
17  76 0
47.00 52 51
18 195 0
57.00 57 60
19 114 0
68.00 65 62
20  85 0
55.00 39 57
(remainder of output deleted)`

You may also wish to consider the programs outfix and outfix2 which can do this for you more easily, but may not work so nicely with large data files and also may require you to edit the resulting raw data file to remove headers and/or footers. You can type findit outfix and findit outfix2 for more information (see How can I use the findit command to search for programs and get additional help? for more information about using findit).

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.