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

我有

var="a b c"

for i in $var

do

p=`echo -e $p'\n'$i`

done

echo $p

我要打印最后一个回声

a

b

c

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

回答:

摘要

  1. 插入 \n

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

    echo -e “${p}”

  2. 在源代码中插入新行

    p="${var1}

    ${var2}”

    echo “${p}”

  3. 使用$'\n'(仅bash和zsh)

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

    echo “${p}”

细节

回答:

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"

回答:

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"

回答:

a

b

c

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


编辑

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

以上是 试图将换行符嵌入bash中的变量中 的全部内容, 来源链接: utcz.com/qa/397697.html

回到顶部