gpt4 book ai didi

bash - 试图在 Bash 的变量中嵌入换行符

转载 作者:IT老高 更新时间:2023-10-28 12:24:55 26 4
gpt4 key购买 nike

我有

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

我想打印最后一个 echo:

a
b
c

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

最佳答案

总结

  1. 在源代码中插入新行

     p="${var1}
    ${var2}"
    echo "${p}"
  2. 使用 $'\n'(仅限 BashZ shell)

     p="${var1}"$'\n'"${var2}"
    echo "${p}"
  3. 使用 echo -e\n 转换为新行

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

详情

  1. 在源代码中插入新行

     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"
  2. 使用 $'\n'(不太便携)

    $'\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"
  3. 使用 echo -e\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"

    ⚠ 在字符串中插入 "\n" 不足以插入新行:"\n" 只是两个字符。

所有输出都相同

a
b
c

特别感谢此答案的贡献者:kevinf , Gordon Davisson , l0b0 , Dolda2000tripleee .


关于bash - 试图在 Bash 的变量中嵌入换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9139401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com