【问题标题】:Using sed to remove line breaks after execute command and save it on array执行命令后使用 sed 删除换行符并将其保存在数组中
【发布时间】:2019-04-14 19:08:33
【问题描述】:

我正在处理一些库存资料,我正在尝试将所有 AWS 区域保存在一个数组中,然后显示一个在另一个下的元素以将其用作输入菜单。

下一个命令给了我正确的输出,但是当我使用 FOR 进入数组时,数组长度仅为 1,因为结果是:

aws ec2 describe-regions --output text|awk -F\t '{print $3}'| sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g'

eu-north-1 ap-south-1 eu-west-3 eu-west-2 eu-west-1 ap-northeast-2 ap-northeast-1 sa-east-1 ca-central-1 a​​p-southeast-1 ap-southeast-2 eu-central-1 us-east-1 us-east-2 us-west-1 us-west-2

这就是我归档数组的方式:

# Get regions
declare -a regions=$(aws ec2 describe-regions --output text | awk -F\t '{print $3}' |  sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /')
echo -e "\nPlease, select the region you would like to query: "

# Print Regions
len=${#regions[@]}
last=$((len+1))
for (( i=0; i<$len; i++ )); do
    echo -e "$i.${regions[$i]}\n" ;
    done
echo -e "$last All of them (this could take a while...O_o)\n"
read region_opt

if [${region_opt}!=${last}] then
    region=(${regions[$region_opt]})

我想在输出中包含类似的东西

  1. eu-north-1
  2. ap-south-1
  3. eu-west-3 ....

【问题讨论】:

  • 当您编写-F\t 时,您是在告诉awk 拆分字母@9​​87654324@ 上的输入,就像您刚刚编写-Ft 一样,因为t 不是元字符。您的意思是写-F'\t' 将输入拆分为制表符吗?无论那个神秘的 sed 脚本在做什么,您都可以在 awk 中清晰易读地完成 - 如果您需要帮助,请发布一个单独的问题。
  • declare -a regions=( $(aws ec2 ...) ) 会将区域填充为 array -- 如果没有 ( $(...) ),您只会填充数组的第一个元素。

标签: arrays bash sed


【解决方案1】:

您的数组值周围缺少括号,例如,

declare -a ARRAY=(value1 value2 ... valueN)

(参考:https://www.tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.htmlhttps://www.gnu.org/software/bash/manual/bash.html

以下形式也可以使用,第一个(没有declare -a)在GNU's Bash reference manualBash guide for beginnersAdvanced bash-scripting guide中作为示例给出:

ARRAY=(value1 value2 ... valueN)
declare ARRAY=(value1 value2 ... valueN)

【讨论】:

  • declare -a 很好。真正的问题是缺少( ..)
  • 这是真的! y 添加另一对 (...) 并工作。谢谢!
  • @NahuelPerez,那么请接受答案。谢谢!
【解决方案2】:

$() 是命令替换,只是将任何标准输出转换为字符串并将其分配给变量
如果你说结果是真的;
eu-north-1 ap-south-1 eu-west-3... 然后从中取出数组,使其在语法上看起来如此,然后告诉 Bash 如此评估它,

regions=($regions)

展开后就是有效的数组语法

 regions=(eu-north-1 ap-south-1 eu-west-3)

然后在被 "" 和 Bash eval 参数包围后将被评估为有效数组

$ eval "regions=($regions)"
$ echo ${regions[0]}
eu-north-1

所以我相信你将能够自己完成和解决它......

【讨论】:

    猜你喜欢
    • 2018-01-21
    • 2011-03-21
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 2023-03-08
    相关资源
    最近更新 更多