我有
var="a b c" for i in $var do p=`echo -e $p'\n'$i` done echo $p
我要打印最后一个回声
a b c
注意,我希望变量p包含换行符。我怎么做?
插入 \n
\n
p="${var1}\n${var2}"
echo -e “${p}”
在源代码中插入新行
p="${var1}
${var2}” echo “${p}”
使用$'\n'(仅bash和zsh)
$'\n'
p="${var1}"$'\n'"${var2}"
echo “${p}”
p="${var1}\n${var2}" echo -e "${p}"
echo -e将两个字符解释"\n"为换行符。
echo -e
"\n"
var="a b c" first_loop=true for i in $var do p="$p\n$i" # Append unset first_loop done echo -e "$p" # Use -e
避免多余的换行符
var="a b c" first_loop=1 for i in $var do (( $first_loop )) && # "((...))" is bash specific p="$i" || # First -> Set p="$p\n$i" # After -> Append unset first_loop done echo -e "$p" # Use -e
使用功能
embed_newline() { local p="$1" shift for i in "$@" do p="$p\n$i" # Append done echo -e "$p" # Use -e } var="a b c" p=$( embed_newline $var ) # Do not use double quotes "$var" echo "$p"
var="a b c" for i in $var do p="$p $i" # New line directly in the source code done echo "$p" # Double quotes required # But -e not required
var="a b c" first_loop=1 for i in $var do (( $first_loop )) && # "((...))" is bash specific p="$i" || # First -> Set p="$p $i" # After -> Append unset first_loop done echo "$p" # No need -e
embed_newline() { local p="$1" shift for i in "$@" do p="$p $i" # Append done echo "$p" # No need -e } var="a b c" p=$( embed_newline $var ) # Do not use double quotes "$var" echo "$p"
bash和zsh解释$'\n'为换行符。
var="a b c" for i in $var do p="$p"$'\n'"$i" done echo "$p" # Double quotes required # But -e not required
var="a b c" first_loop=1 for i in $var do (( $first_loop )) && # "((...))" is bash specific p="$i" || # First -> Set p="$p"$'\n'"$i" # After -> Append unset first_loop done echo "$p" # No need -e
embed_newline() { local p="$1" shift for i in "$@" do p="$p"$'\n'"$i" # Append done echo "$p" # No need -e } var="a b c" p=$( embed_newline $var ) # Do not use double quotes "$var" echo "$p"
特别感谢以下答案的贡献者:kevinf,GordonDavisson,l0b0,Dolda2000和Tripleee。
编辑
for