[英]How do I add newline character at end of lines in blockquote for printing?
I'm using MacOS and Bash 4.4.23.我使用的是 MacOS 和 Bash 4.4.23。
I want to be able to have a long blockquote in a single string for a help dialogue and print that in the program.我希望能够在单个字符串中包含一个长块引用以用于帮助对话并将其打印在程序中。
Suppose I have a string in var help
假设我在 var
help
有一个字符串
help='Searches a user to
see if he exists.'
help2='Searches a user to\n
see if he exists.'
echo $help # all one line
echo $help2 # all one line (with literal \n)
printf $help # prints 'Searches'
printf $help2 # same ^
I also tried我也试过
help3=$'Searches a user\n
to see if he exists.'
but I still don't get my expected results.但我仍然没有得到我预期的结果。
What I want to be printed:我想打印的内容:
Searches a user to
see if he exists.
$help
is set correctly; $help
设置正确; what needs fixing is when it's expanded.需要修复的是它何时扩展。 As a rule of thumb you should almost always quote variables when they're expanded.
根据经验,当变量被扩展时,你几乎总是应该引用它们。 Doing so here will preserve the embedded newline(s).
在此处这样做将保留嵌入的换行符。
help='Searches a user to
see if he exists.'
echo "$help"
Looking through for string splitting options, I found I could do this查看字符串拆分选项,我发现我可以做到这一点
help='Searches a user
to see if he exists.'
IFS=$'\n'
printf '%s\n' $help
unset IFS
you can also do a for line in $help; do echo $line done
你也可以
for line in $help; do echo $line done
做一个for line in $help; do echo $line done
for line in $help; do echo $line done
instead of the using the printf
command. for line in $help; do echo $line done
而不是使用printf
命令。
src: https://unix.stackexchange.com/questions/184863/what-is-the-meaning-of-ifs-n-in-bash-scripting源代码: https : //unix.stackexchange.com/questions/184863/what-is-the-meaning-of-ifs-n-in-bash-scripting
src2: How can I have a newline in a string in sh? src2: 如何在 sh 的字符串中添加换行符?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.