Search code examples
shellsh

How to read array records with specific header name


I have specific records as below in one array $rolerows each record delimited by new line:

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

I like to create a new array which will split each record by header. Consecutive delimiters(space) should be as one since it does not really have any delimiter. Start of new header value defined new field.

name, roletemplateappID, roleTemplateName,description

exact Length of each column is not known but it will be based on where column first line of header it starts as shown in my sample data.

How do I create new array which is organized in 4 separate column ?


Solution

  • The first three fields are white-space delimited and the last one takes the rest, so you could do something like this:

    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