Search code examples
bashawkldif

From file to ldif script, attributes separated by comma


I have a file like this:

h3fah055,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_DWH h3fah058,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_DWH h3fah065,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_ERP h3fah066,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_ERP h3fah082,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG h3fal029,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG h3fal030,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG

I would like to generate an ldif from this file, so for each rows I need to generate:

 dn: cn=h3fah055,ou=hosts,dc=example,dc=com
 objectClass: host
 objectClass: ipHost
 objectClass: top
 ipHostNumber: 1.1.1.1
 cn: h3fah055
 Allowednetgroup: NG_SYS_UX
 Allowednetgroup: NG_SYS_FO
 Allowednetgroup: NG_SYS_STG
 Allowednetgroup: NG_APP_DWH

How can I read each rows in this file and save, if existing, each netgroup in a variable in order to print in a file my desired output?

I tryed with

while read p; do
  echo $p |  awk -F , '{print "dn: cn=" $1 ",ou=hosts,dc=example,dc=com"}'
done <hosts_list.txt

But I'm not sure how to add as many Allowednetgroup as defined in the file.


Solution

  • awk has a variable NF which is the number of fields on the line. So you can loop through them with a for statement like this.

    awk -F',' '{print "dn: cn=" $1 ",ou=hosts,dc=example,dc=com\nobjectClass:host\nobjectclass: ipHost\nobjectClass: top\nipHostNumber 1.1.1.1\ncn:" $1;
        for(i=2;i<=NF;i++) print "Allowednetgroup: " $i  }' hosts_list.txt
    

    Notice that awk will read each line itself so you don't need pass one line at a time like your MVCE. Just pass the filename as a second argument. i.e. awk '<script>' filename

    The above script will produce output like:

    dn: cn=h3fah055,ou=hosts,dc=example,dc=com
    objectClass:host
    objectclass: ipHost
    objectClass: top
    ipHostNumber 1.1.1.1
    cn:h3fah055
    Allowednetgroup: NG_SYS_UX
    Allowednetgroup: NG_SYS_FO
    Allowednetgroup: NG_SYS_STG
    Allowednetgroup: NG_APP_DWH
    etc...