一尘不染

试图将换行符嵌入bash中的变量中

linux

我有

var="a b c"
for i in $var
do
   p=`echo -e $p'\n'$i`
done
echo $p

我要打印最后一个回声

a
b
c

注意,我希望变量p包含换行符。我怎么做?


阅读 375

收藏
2020-06-02

共1个答案

一尘不染

摘要

  1. 插入 \n

    p="${var1}\n${var2}"
    

    echo -e “${p}”

  2. 在源代码中插入新行

    p="${var1}
    

    ${var2}”
    echo “${p}”

  3. 使用$'\n'(仅bashzsh

    p="${var1}"$'\n'"${var2}"
    

    echo “${p}”

细节

1.插入 \n

p="${var1}\n${var2}"
echo -e "${p}"

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"

2.在源代码中插入新行

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"

3.使用$'\n'(便携式性较低)

bashzsh解释$'\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"

所有输出都相同

a
b
c

特别感谢以下答案的贡献者:kevinf,GordonDavisson,l0b0,Dolda2000和Tripleee。


编辑

  • 另请参见BinaryZebra的答案,其中提供了许多详细信息。
  • Abhijeet Rastogi的答案和Dimitry的答案说明了如何避免for上述bash片段中的循环。
2020-06-02