How would you include newline characters in a C-shell echo command?

冷暖自知 提交于 2019-11-28 09:06:49

问题


This sounds ridiculously easy, and it is with other shells. But I can't seem to figure out how to get echo to display newlines. For example -

cat myFile

shows the file as it actually exists, which is what I want -

this
is
my
file

whereas my script, which contains the following -

#!/bin/csh
set var = `cat myFile`
echo "$var"

removes all the newlines, which is not what I want -

this is my file

Thanks in advance.


回答1:


The problem isn't with the echo command, it's with csh's handling of backticks. When you execute

set var = `cat myFile`

the newlines from myfile are never stored in $var; they're converted to spaces. I can't think of any way to force a csh variable to include newlines read from a file, though there might be a way to do it.

sh and its derivatives do behave the way you want. For example:

$ x="`printf 'foo\nbar'`"
$ echo $x
foo bar
$ echo "$x"
foo
bar
$ 

The double quotes on the assignment cause the newlines (except for the last one) to be preserved. echo $x replaces the newlines with spaces, but echo "$x" preserves them.

Your best bet is to do something other than trying to store the contents of a file in a variable. You said in a comment that you're trying to send an e-mail with the contents of a log file. So feed the contents of the file directly to whatever mail command you're using. I don't have all the details, but it might look something like this:

( echo this ; echo that ; echo the-other ; cat myFile ) | some-mail-command

Obligatory reference: http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/




回答2:


You can use Awk to delimit each line with '\n' before the shell strings them together.

set var = `cat myfile | awk '{printf("%s\\n", $0)'}`

Assuming your echo command will interpret "\n" as a newline character, echo ${var} should reproduce cat myfile without the need for additional file access. If the newline code is not recognized, you can try adding the -e flag to echo and/or using /bin/echo.



来源:https://stackoverflow.com/questions/9980537/how-would-you-include-newline-characters-in-a-c-shell-echo-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!