【问题标题】:Split string in Array after specific delimited and New line在特定分隔和新行之后拆分数组中的字符串
【发布时间】:2021-10-20 15:27:28
【问题描述】:
$string="name: Destination Administrator
    description: Manage the destination configurations, certificates and subaccount trust.
    readOnly:
    roleReferences:
    - roleTemplateAppId: destination-xsappname!b62
      roleTemplateName: Destination_Administrator
      name: Destination Administrator"

我有上面的字符串,每一行都由换行符分隔,我喜欢在“-”之后创建两列的数组,如下所示

Col1                    col2
roleTemplateAppId       destination-xsappname!b62
roleTemplateName        Destination_Administrator
name                    Destination Administrator

我在下面尝试过,但它没有返回正确的数组

IFS='- ' read -r -a arrstring <<< "$string"
echo "${arrstring [1]}"

【问题讨论】:

  • 这是哪个 shell 脚本变体?您应该标记您的问题 [bash]、[zsh] 等。
  • 对不起,我添加为 Bash
  • 您的数据是 YAML,请使用 YAML 解析器。 Bash/shell 无法解析 YAML。
  • array with two column 是什么意思?第一列应该是数组的索引吗?
  • 我的示例中显示的数据的二维数组。 Col1 和 col2 显示的值。

标签: bash split yaml


【解决方案1】:

假设:

  • OP 无法使用 yaml 解析器(根据 Léa 的评论)
  • 输入保证有\n 行结尾(在数据内)
  • - 仅显示在一个位置(如 OP 的示例输入所示);否则我们需要更好地定义从哪里开始解析数据
  • 我们有兴趣解析- 之后的所有内容
  • 数据将基于: 分隔符进行解析,第一个字段作为关联数组中的索引,而第二个字段将作为存储在数组中的值
  • 要从数组索引和值中删除前导/尾随空格

一个sed 的想法是只提取我们感兴趣的行:

$ sed -n '/- /,${s/-//;p}' <<< "${string}"
     roleTemplateAppId: destinationxsappname!b62
      roleTemplateName: Destination_Administrator
      name: Destination Administrator

添加更多位以去除前导/尾随空格:

$ sed -n '/- /,${s/-//;s/^[ ]*//;s/[ ]*$//;s/[ ]*:[ ]*/:/;p}' <<< "${string}"                                          
roleTemplateAppId:destination-xsappname!b62
roleTemplateName:Destination_Administrator
name:Destination Administrator

从这里我们将它提供给while 循环,我们将在其中填充关联数组

unset      arrstring
declare -A arrstring                   # declare as an associative array

while IFS=':' read -r index value
do
    arrstring["${index}"]="${value}"
done < <(sed -n '/- /,${s/-//;s/^[ ]*//;s/[ ]*$//;s/[ ]*:[ ]*/:/;p}' <<< "${string}")

留给我们:

$ typeset -p arrstring
declare -A arrstring=([roleTemplateAppId]="destination-xsappname!b62" [name]="Destination Administrator" [roleTemplateName]="Destination_Administrator" )

$ for i in "${!arrstring[@]}"
do
    echo "$i : ${arrstring[$i]}"
done

roleTemplateAppId : destination-xsappname!b62
name : Destination Administrator
roleTemplateName : Destination_Administrator

【讨论】:

  • 这是一个很好的解决方案。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多