【问题标题】:Replace Newline With Space In Array Element In a For Loop In Bash在 Bash 的 For 循环中用数组元素中的空格替换换行符
【发布时间】:2018-10-30 17:09:21
【问题描述】:

我在 for 循环中为数组赋值:

aws_user_roles+=("$aws_role_name")

如果我从命令中分配数组的值并想删除换行符,我可以这样做:

 readarray -t aws_roles < <(...some aws commands...)

我的 for 循环看起来像这样:

for ((has_role_index=0;has_role_index<${#aws_user_has_roles[@]};++has_role_index)); do         
             aws_user_roles+=("$aws_role_name")
             declare -p aws_user_roles
done

如何从aws_user_roles 中的数组元素中去掉换行符并用空格替换它?

【问题讨论】:

  • 您真的想用空格替换换行符,还是希望每一行都是一个单独的数组元素?

标签: arrays bash for-loop


【解决方案1】:

使用tr:

aws_user_roles+=("$(<<<"$aws_role_name" tr '\n' ' ')")
  • $(..) 是命令替换
  • &lt;&lt;&lt;"$variable" 是这里的字符串
  • tr '\n' ' ' 用换行符代替空格。

【讨论】:

    【解决方案2】:

    使用模式替换:

    aws_user_roles+=("${aws_role_name//$'\n'/ }")
    

    来自man bash

    ${参数/模式/字符串}

    模式替换。该模式被扩展以产生一个模式,就像在路径名扩展中一样。参数被扩展,模式与其值的最长匹配被替换为字符串。如果pattern 以/ 开头,则pattern 的所有匹配都被替换为字符串。通常只替换第一个匹配项

    【讨论】:

      猜你喜欢
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 2014-12-19
      相关资源
      最近更新 更多