1

I have two files, one, file1 is 1000 lines with router configurations in it. A portion of it is like this -

 !
 ipv6 prefix-list CCAV6 seq 5 permit 2217:AB23::/40
 route-map DENY-ALL deny 11
 !
 ip pim sparse-mode
 ipv6 address 2617:FB23:0:1::1/128
 ipv6 ospf 1 area 0.0.0.0

and so on. My second file file2 is a mapping of ipv6 to ipv4 addresses. It looks like this-

 2617:FB23:0:1::1/128 245.82.242.31/32
 2217:AB23::/40 64.211.7.157/31

I want to be able to replace the traverse file1 and if my first column of file2 matches any part of file1, it should replace it with the second column of file2

for example, the output I expect to see after processing would be-

!
ipv6 prefix-list CCAV6 seq 5 permit 64.211.7.157/31
route-map DENY-ALL deny 11
!
ip pim sparse-mode
ipv6 address 245.82.242.31/32
ipv6 ospf 1 area 0.0.0.0

I have tried using awk but all the options I have come across seem to require prior knowledge of the position of the replication and the position of the first column doesnt remain the same through out file1. I would appreciate some ideas.

3 Answers 3

1

If you're not too bothered by multi-space/tab field separators from file1 being replaced with single spaces:

awk 'NR == FNR{a[$1]=$2; next}; 
  {for (i=1; i<=NF; ++i) printf "%s%s", $i in a?a[$i]: $i, i == NF?"\n": " "}' file2 file1

yields

!
ipv6 prefix-list CCAV6 seq 5 permit 64.211.7.157/31
route-map DENY-ALL deny 11
!
ip pim sparse-mode
ipv6 address 245.82.242.31/32
ipv6 ospf 1 area 0.0.0.0
1
  • Or ... {for(i=1;i<=NF;++i) if($i in a) $i=a[$i]; print} and let awk's automatic regeneration of $0 do the formatting. Apr 19, 2016 at 9:12
1

The following script will read each of the first two words into a hash and then it will substitute the IPV6 for the IPV4 and will stop checking for other patterns, if you consider that two addresses might exist in the same line please remove if (j>0) break, from the code.

mixaddr code

#!/usr/bin/nawk -f
BEGIN{while (getline<"map"){w[$1]=$2}}
{for (a in w){
    j=gsub(a,w[a])
    if (j>0) break
    }
    print
}

map file

2617:FB23:0:1::1/128 245.82.242.31/32
2217:AB23::/40 64.211.7.157/31

hosts file

!
ipv6 prefix-list CCAV6 seq 5 permit 2217:AB23::/40
route-map DENY-ALL deny 11
!
ip pim sparse-mode
ipv6 address 2617:FB23:0:1::1/128
ipv6 ospf 1 area 0.0.0.0

Execution

mixaddr hosts
!
ipv6 prefix-list CCAV6 seq 5 permit 64.211.7.157/31
route-map DENY-ALL deny 11
!
ip pim sparse-mode
ipv6 address 245.82.242.31/32
ipv6 ospf 1 area 0.0.0.0

HTH

0
#!/bin/bash
IFS=$'\n'
line=`cat ./file2`
for var in $line 
do
string1=`echo $var |awk '{print $1}'`
string2=`echo $var |awk '{print $2}'`
sed -i "s#${string1}#${string2}#g" ./file1
done

You need backup the file1 before run this.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .