简体   繁体   English

Bash-如何使用printf打印多行字符串(带有'\\ n')

[英]Bash - How to print multi line strings (with '\n') using printf

i'm trying to print a multi line strings in printf this way 我正在尝试以这种方式在printf打印多行字符串

printf "hi\n"
printf "next line here\n"

I can't do the following 我不能执行以下操作

text_content="
hi
next line here
"

printf $text_content

Is there any other way? 还有其他办法吗?

Quoting the variable should do the trick. 引用变量应该可以解决问题。 In your example, however, you are getting double newlines. 但是,在您的示例中,您将获得双换行符。

printf "$text_content"

If printf is not necessary, then you may use echo: 如果不需要printf,则可以使用echo:

var="one\ntwo"
echo -e $var

Here's another variation. 这是另一种变化。

printf '%s\n' 'first line here' 'second line here'

You can add an arbitrary number of arguments; 您可以添加任意数量的参数。 printf will repeat the format string until all arguments are exhausted. printf将重复格式字符串,直到用完所有参数为止。

printf '%s\n' '#!/bin/sh' \
    'for x; do' \
    '    echo "Welcome to my script!"' \
    'done' >script.sh

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM