删除bash数组元素之间的空格

时间:2013-08-05 15:56:36

标签: regex arrays bash

我正在尝试找到一种方法,在我用于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的print语句添加到我的代码中,以便

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”后运行脚本时给我一个“:命令未找到错误”

2 个答案:

答案 0 :(得分:0)

这就是echo与数组一起工作的方式。像这样使用printf

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

你应该看到:

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

答案 1 :(得分:0)

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

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[@]}"
相关问题