3

我对此很陌生,所以谢谢你的耐心

我有一个包含数百个值的文本文件,我想从中填充一个 ldif 模板。所以例如文件 example1.txt 有

**Consumer1**

**Consumer2**

并且 ldif.txt 有

***dn: ,cn=Insert,o=Insert
uid:
userPassword:
objectclass: top
objectclass: inetOrgPerson
objectclass: person
objectclass: organizationalPerson
businessCategory:
sn:
cn:***

***dn: ,cn=Insert,o=Insert
uid:
userPassword:
objectclass: top
objectclass: inetOrgPerson
objectclass: person
objectclass: organizationalPerson
businessCategory:
sn:
cn:***

对于这个例子,我想遍历 example1.txt 和 sed,以便它第一次遇到“dn:”时将其替换为“dn:consumer1”,然后是第二个“dn:consumer2”等等,所以我想要它之后看起来像这样

*dn:**consumer1** ,cn=Insert,o=Insert
uid:
userPassword:
objectclass: top
objectclass: inetOrgPerson
objectclass: person
objectclass: organizationalPerson
businessCategory:
sn:
cn:*

*dn:**consumer2** ,cn=Insert,o=Insert
uid:
userPassword:
objectclass: top
objectclass: inetOrgPerson
objectclass: person
objectclass: organizationalPerson
businessCategory:
sn:
cn:*

我已经尝试过了,但它只是循环遍历文件并将所有条目替换为 dn:consumer2 而不是 1,而不是 2。

for i in `cat example1.txt`
do
sed "s/dn:/dn: $i/" ldif.txt > hello.txt
done

这输出以下内容

*dn:**consumer2** ,cn=Insert,o=Insert
uid:
userPassword:
objectclass: top
objectclass: inetOrgPerson
objectclass: person
objectclass: organizationalPerson
businessCategory:
sn:
cn:*

*dn:**consumer2** ,cn=Insert,o=Insert
uid:
userPassword:
objectclass: top
objectclass: inetOrgPerson
objectclass: person
objectclass: organizationalPerson
businessCategory:
sn:
cn:*

有什么方法可以让它逐步循环并来回替换,以便我们获得第一次点击dn:consumer1, 2nd hit dn:consumer2等?

4

1 回答 1

3

以下是使用 awk 的方法:

$ awk 'NR==FNR{a[NR]=$0;next}$1=="***dn:"{$1="*dn:"a[++k]}1' example1.txt ldif.txt 
*dn:**Consumer1** ,cn=Insert,o=Insert
uid:
userPassword:
objectclass: top
objectclass: inetOrgPerson
objectclass: person
objectclass: organizationalPerson
businessCategory:
sn:
cn:***

*dn:**Consumer2** ,cn=Insert,o=Insert
uid:
userPassword:
objectclass: top
objectclass: inetOrgPerson
objectclass: person
objectclass: organizationalPerson
businessCategory:
sn:
cn:***
于 2013-10-25T16:12:53.307 回答