我是新手,所以,谢谢你的耐心
我有一个包含数百个值的文本文件,我想从中填充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:***
对于这个例子,Id喜欢循环执行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替换所有条目。
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
等的第一个命中?
答案 0 :(得分: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:***