增加匹配第一列的第二列

时间:2014-06-17 11:45:20

标签: linux shell

我有下面给出的数据的文本文件,我想将uidNumber增加9000 ,所有数据应该保持不变。

输入文件:

cn: cn=DINAKAR PERI_DPA062,ou=DBS,dc=xyz,dc=com

objectClass: posixAccount

objectClass: inetOrgPerson

objectClass: extensibleObject

cn: DINAKAR PERI

uidNumber: 1001

dn: cn=JOSEPH ABBY_AJA059,ou=TSR,dc=xyz,dc=com

objectClass: posixAccount

objectClass: inetOrgPerson

objectClass: extensibleObject

cn: JOSEPH ABBY

uidNumber: 1002

.

.

.

.

输出文件:

only uidNumber should be like this 

cn: cn=DINAKAR PERI_DPA062,ou=DBS,dc=xyz,dc=com

objectClass: posixAccount

objectClass: inetOrgPerson

objectClass: extensibleObject

cn: DINAKAR PERI

uidNumber: 10001

dn: cn=JOSEPH ABBY_AJA059,ou=TSR,dc=xyz,dc=com

objectClass: posixAccount

objectClass: inetOrgPerson

objectClass: extensibleObject

cn: JOSEPH ABBY

uidNumber: 10002

.

.

.

.

2 个答案:

答案 0 :(得分:2)

awk '/uidNumber/{$2+=9000}1' infile

这里有两个单独的行动:

  1. /uidNumber/{$2+=9000}:只有在找到模式时才会增加第二个字段 (numeracilly)

  2. 1:始终打印当前行。

答案 1 :(得分:1)

如果您的数据在文件" testdata"中,则:

使用纯粹的bash:

RE="uidNumber:"
while read -r line
do
    if [[ $line =~ $RE ]]
    then
        read -r key val <<< "$line"
        val=$(( $val + 9000 ))
        echo "$key $val"
    else
        echo "$line"
    fi
done < testdata

检查:

diff <(bash incscript.sh) testdata

打印:

11c11
< uidNumber: 10001
---
> uidNumber: 1001
23c23
< uidNumber: 10002
---
> uidNumber: 1002

并且,也可以使用perl,例如:

perl -plE 's/(\d+)/@{[$1+9000]}/c if /uidNumber/'

检查:

diff <(perl -plE 's/(\d+)/@{[$1+9000]}/c if /uidNumber/' < testdata) testdata

打印:

11c11
< uidNumber: 10001
---
> uidNumber: 1001
23c23
< uidNumber: 10002
---
> uidNumber: 1002