In bash, I have a string containing \n characters. When I echo -e $mystring it formats as I expect in the console, respecting the newline characters. However, when I redirect the output to a file, the resulting file is all one line, minus the \n characters, even if I use the -e flag:

echo -e $mystring > myfile.txt

However, tabs \t are respected. How can I get the formatting right in the file?

link|improve this question
feedback

2 Answers

up vote 1 down vote accepted

Double quotes (") should help.

$> mystring="\na\tb\nok"
$> echo -e "$mystring" > ./file
$> cat ./file 

a   b
ok

You should use \r\n instead of \n for "Windows newlines".

link|improve this answer
It shows up ok in cat, but when you open with a text editor it is all one line... – Benjamin Dec 1 '11 at 22:05
It's something with your text editor. Seems work fine in vim, actually. – ДМИТРИЙ МАЛИКОВ Dec 1 '11 at 22:08
So how do I get a format that will respect newlines on a Windows machine and a Linux machine? – Benjamin Dec 1 '11 at 22:10
Is the text editor notepad? If so, it needs CR LF, not just CR – Paul Dec 1 '11 at 22:11
"Newlines on a Windows machine" is a "\r\n". – ДМИТРИЙ МАЛИКОВ Dec 1 '11 at 22:11
feedback

If you want text files that are created on *nix machines to be viewed on Windows machines then use the unix2dos utility.

If you want to view text files on *nix machines that are created on Windows machines then use dos2unix utility.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.