2

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?

1 Answer 1

3

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".

5
  • It shows up ok in cat, but when you open with a text editor it is all one line...
    – Benjamin
    Dec 1, 2011 at 22:05
  • It's something with your text editor. Seems work fine in vim, actually. Dec 1, 2011 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, 2011 at 22:10
  • Is the text editor notepad? If so, it needs CR LF, not just CR
    – Paul
    Dec 1, 2011 at 22:11
  • "Newlines on a Windows machine" is a "\r\n". Dec 1, 2011 at 22:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .