Tuesday, June 24, 2008

Update a file based on another file-sed


First file:

$ cat ranks.txt
172.22.22.12:1
172.22.22.13:1
172.22.22.16:2
172.22.22.10:1
172.22.22.18:3


Second file (Exception file)

$ cat except_ip.txt
172.22.22.13
172.22.22.12


Requirement:

- based on the entries in the second file, i.e. except_ip.txt, update the second fileld of first file i.e. ranks.txt in such a way that : if the IP address is present in the second file, make the rank(2nd field of ranks.txt) to 0, rest entries in ranks.txt should be unchanged.

i.e.

required output:

172.22.22.12:0
172.22.22.13:0
172.22.22.16:2
172.22.22.10:1
172.22.22.18:3


The awk code:

$ awk 'BEGIN {FS=OFS=":"}
FNR==NR {ex[$1]; next}
{ $2 = ($1 in ex) ? "0" : $2; print }
' except_ip.txt ranks.txt

172.22.22.12:0
172.22.22.13:0
172.22.22.16:2
172.22.22.10:1
172.22.22.18:3


.

No comments:

© Jadu Saikia www.UNIXCL.com