shell 如何读取具有特定头名称的数组记录

hi3rlvi2  于 2023-10-23  发布在  Shell
关注(0)|答案(1)|浏览(125)

我在一个数组$rolerows中有如下特定的记录,每个记录由新行分隔:

name                                             roleTemplateAppId          roleTemplateName                                 description          

AccessAllAccessPoliciesArtifacts                 it!b2455                   AccessAllAccessPoliciesArtifacts                 Role for accessing artifacts despite access policies are maintained                      

AccessPoliciesEdit                               it!b2455                   AccessPoliciesEdit                               Role for maintaining/creating access policies                                  

AccessPoliciesRead                               it!b2455                   AccessPoliciesRead                               Role for reading access policies

我想创建一个新的数组,将每个记录的标题。连续分隔符(空格)应该是一个,因为它实际上没有任何分隔符。新标题值的开始定义了新字段。
name,roletemplateappID,roleTemplateName,description
每个列的确切长度是未知的,但它将基于列标题的第一行,它开始在我的示例数据所示。
我如何创建一个新的数组,它是组织在4个单独的列?

5t7ly7z5

5t7ly7z51#

前三个字段是用空格分隔的,最后一个字段占用其余的字段,所以你可以这样做:

while read -r a b c d
do
    printf '%s,%s,%s,%s\n' "$a" "$b" "$c" "$d"
done < file.txt
name,roleTemplateAppId,roleTemplateName,description
AccessAllAccessPoliciesArtifacts,it!b2455,AccessAllAccessPoliciesArtifacts,Role for accessing artifacts despite access policies are maintained
AccessPoliciesEdit,it!b2455,AccessPoliciesEdit,Role for maintaining/creating access policies
AccessPoliciesRead,it!b2455,AccessPoliciesRead,Role for reading access policies

相关问题