How to output a new line in a .txt file with \immediate\write18

I am trying to create a text file foobar.txt using \immediate\write18, and can not figure out how to properly get the \n so that Unix puts these lines on a new line. The MWE below produces one line in the output file:

\n \n ---------\n Foo: foo \n Foo: foo \n Bar: bar \n

What I want in the output file is a few blank lines followed by:

---------

Foo: foo

Bar: bar

• This appears to always append to the file, where as I thought the normal Unix way is that single > overwrites the file, and the double >> appends to the file. How can I get it to overwrite the file if it already exists. Or is this a security feature that prohibits this.

Notes:

• The values after the colon are not fixed, but are built during compile time. Otherwise a simple cat solution would have worked.

Code:

\documentclass{article}

\begin{document}
\immediate\write18{%
echo "         \string\n" >  foobar.txt%
echo "         \string\n" >> foobar.txt%
echo "---------\string\n" >> foobar.txt%
echo "Foo: foo \string\n" >> foobar.txt%
echo "Foo: foo \string\n" >> foobar.txt%
echo "Bar: bar \string\n" >> foobar.txt%
}
\end{document}

-
Why not use the filecontents package? –  Werner Jul 12 '12 at 22:58
Why not using the standard \write mechanism? –  egreg Jul 12 '12 at 23:03
In Unix, echo's default behaviour is to disable the interpretation of backslash escapes, so echo "a\nb\nc" will print the line as it is. If you want to enable the escapes, add the -e flag to echo. :) –  Paulo Cereda Jul 13 '12 at 0:59
@Werner: The content of the file is not fixed, but is obtained from parameters passed to the macro that writes the file. There is probably some expansion magic that would allow me to use the filecontents package, but using echo was simpler. –  Peter Grill Jul 18 '12 at 1:35

Just concatenate the echo commands:

\documentclass{article}

\begin{document}
\immediate\write18{%
echo "" >  foobar.txt;
echo "" >> foobar.txt;
echo "--------" >> foobar.txt;
echo "Foo: foo" >> foobar.txt;
echo "Foo: foo" >> foobar.txt;
echo "Bar: bar" >> foobar.txt
}
\end{document}


If the noclobber variable is set, the shell will refuse to overwrite an existing file with an output redirection command. So if the variable is set in the environment of the called command shell, the first echo "" > foobar.txt will not succeed.

However the same result will be obtained with the standard stream writing:

\newwrite\foobar
\immediate\openout\foobar=foobar.txt
\immediate\write\foobar{}
\immediate\write\foobar{}
\immediate\write\foobar{--------}
\immediate\write\foobar{Foo: foo}
\immediate\write\foobar{Foo: foo}
\immediate\write\foobar{Foo: bar}
\immediate\closeout\foobar

-
I was unable to use the standard writing stream as it prohibited writing in a directory above the current one. But the echo solution you posted works great (not that there was any doubt :-)). –  Peter Grill Jul 18 '12 at 1:36