【问题标题】:Remove whitespace between bash array elements删除 bash 数组元素之间的空格
【发布时间】:2013-08-06 09:59:48
【问题描述】:

我正在尝试找到一种方法,使我用于 AWS CLI 命令的 bash 数组的元素之间没有空格。该命令的过滤器抱怨过滤器必须采用格式“--filters name=string1,values=string1,string2”。

我目前拥有的代码:

tag_filter=( $(aws ec2 describe-tags --filter "name=value,values=${tags[@]}" | jq '[.Tags[] | {ResourceId}]') )
regex=[[:alpha:]][-][[:xdigit:]]
for x in ${tag_filter[@]}
do
  if [[ $x =~ $regex ]]
  then
    #parameter expansion to remove " from elements
    resource_id+=( "${x//\"}," )
    #$resource_id== "${resource_id_array[@]// /,}" 
  else
    throw error message
  fi
done
echo "${resource_id[@]}"

这给了我

的输出
foo-bar, herp-derp, bash-array,

但它必须是

foo-bar,herp-derp,bash-array,

让下一个过滤器命令生效。我的搜索结果是删除字符串中的空格、将字符串转换为数组或一般的数组文档,而我在任何地方都没有看到类似的问题。

编辑:

我已将 anubhava 的打印语句添加到我的代码中,这样

then
  #parameter expansion to remove " from elements
  resource_id_array+=( "${x//\"}," )
  resource_id= $( printf "%s" "${resource_id_array[@]}" )
  resource_id= ${resource_id:1}
  #${resource_id[@]}== "${resource_id[@]// /,}" 
else

它现在给了我需要的输出,但是当我在回显“$resource_id”后运行脚本时给我一个“:command not found error”

【问题讨论】:

    标签: regex arrays bash


    【解决方案1】:

    这就是 echo 处理数组的方式。像这样使用printf

    printf "%s" "${resource_id[@]}" && echo ""
    

    你应该看到:

    foo-bar,herp-derp,bash-array,
    

    【讨论】:

    • 这适用于获取数组的输出,但我需要数组本身采用该格式。
    • 数组只有单个元素。您是否也注意到单个元素中的尾随空格?尝试将其打印为:echo "@${resource_id[0]}@" 以进行验证。
    【解决方案2】:

    所以我最终做的是基于 anubhava 的回答和 cmets

    tag_filter=( $(aws ec2 describe-tags --filter "name=value,values=${tags[@]}" | jq '[.Tags[] | {ResourceId}]') )
    regex=[[:alpha:]][-][[:xdigit:]]
    for x in ${tag_filter[@]}
    do
      if [[ $x =~ $regex ]]
      then
        #parameter expansion to remove " from elements
        resource_id+=( "${x//\"}" ) 
      else
        throw error message
      fi
    done
    
    resource_id=$( printf "%s" "${resource_id_array[@]}" )
    echo "${resource_id[@]}"
    

    【讨论】: