Appending a line break to an output file in a shel

2019-03-11 23:22发布

I have a shell script that I am executing in Cygwin (maybe this is the problem). For this bit of code, I simply want to write the first line, and append a line break:

echo "`date` User `whoami` started the script." >> output.log
echo >> output.log

But the output.log file never seems to take the break. If I run the script multiple times, it's as if the second echo doesn't write to the file.

I've also tried:

echo -e "`date` User `whoami` started the script.\n" >> output.log

It yields the same results.

The odd thing is if I just enter the second echo statement above on the command line, without appending to the file, it gives me the expected output with the trailing line break.

4条回答
淡お忘
2楼-- · 2019-03-11 23:58

I'm betting the problem is that Cygwin is writing Unix line endings (LF) to the file, and you're opening it with a program that expects Windows line-endings (CRLF). To determine if this is the case — and for a bit of a hackish workaround — try:

echo "`date` User `whoami` started the script."$'\r' >> output.log

(where the $'\r' at the end is an extra carriage-return; it, plus the Unix line ending, will result in a Windows line ending).

查看更多
Anthone
3楼-- · 2019-03-11 23:58

Try:

echo "`date` User `whoami` started the script."$'\n' >> output.log

or just:

echo $'\n' >> output.log
查看更多
smile是对你的礼貌
4楼-- · 2019-03-12 00:09

Try

echo -en "`date` User `whoami` started the script.\n" >> output.log

Try issuing this multiple times. I hope you are looking for the same output.

查看更多
萌系小妹纸
5楼-- · 2019-03-12 00:14

You can do that without an I/O redirection:

sed -i 's/$/\n/' filename

You can also use this command to append a newline to a list of files:

find dir -name filepattern | xargs sed -i 's/$/\n/' filename

For echo, some shells implement it as a shell builtin command. It might not accept the -e option. If you still want to use echo, try to find where the echo binary file is, using which echo. In most cases, it is located in /bin/echo, so you can use /bin/echo -e "\n" to echo a new line.

查看更多
登录 后发表回答