将文件中的数据输入到标签中

将文件中的数据输入到标签中

我的文件包含有关用户的大量数据。例如:

Username:Firstname:Lastname:Telephone number
Username:John:anderson:857-201-2213
Username:Sam:Asper:876-590-8223
Username:Adam:marlen:871-343-2233
Username:Suzi:sanders:991-531-9821
Username:paul:sepan:992-432-2267

我想为每个用户创建标签。如何从上面的输入文件中读取数据并为每个用户生成标签,如下所示:

dn: uid=John anderson, dc=example, dc=com
cn: John anderson
sn: anderson
telephoneNumber: 857-201-2213

===================
dn: uid=Adam marlen, dc=example, dc=com
cn: Adam marlen
sn: marlen
telephoneNumber: 871-343-2233

===================

答案1

单独使用 Awk:

awk -F: '
  NR > 1 {
    printf("dn: uid=%s, dc=example, dc=com\ncn: %s\nsn: %s\ntelephoneNumber: %s\n", 
              $2 " " $3, $2 " " $3, $3, $4); 
    print "\n===================";
  }
' file

答案2

你可以这样做:

#!/bin/bash
cat file | sed '1d;/^\s*$/d;s/:/\t/g' | while IFS='\t' read line; do

firstname=$(echo $line | awk '{print $2}')
secondname=$(echo $line | awk '{print $3}')
phone=$(echo $line | awk '{print $4}')

echo "
dn: uid=$firstname $secondname, dc=example, dc=com
cn: $firstname $secondname
sn: $secondname
telephoneNumber: $phone

==================="    
done

输出:

dn: uid=John anderson, dc=example, dc=com
cn: John anderson
sn: anderson
telephoneNumber: 857-201-2213

===================

dn: uid=Sam Asper, dc=example, dc=com
cn: Sam Asper
sn: Asper
telephoneNumber: 876-590-8223

===================

dn: uid=Adam marlen, dc=example, dc=com
cn: Adam marlen
sn: marlen
telephoneNumber: 871-343-2233

===================

dn: uid=Suzi sanders, dc=example, dc=com
cn: Suzi sanders
sn: sanders
telephoneNumber: 991-531-9821

===================

dn: uid=paul sepan, dc=example, dc=com
cn: paul sepan
sn: sepan
telephoneNumber: 992-432-2267

===================

相关内容