Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python replace multiple patterns in the lines of a file

Tags:

python

file

Here is a problem which is annoying me during these last two hours. I have a template file with multiple lines and in some lines some words have to be changed by some others. Here is how my template looks like:

subnet {{ MY_SUBNET }} netmask {{ MY_NETMASK }} {}

subnet {{ MY_SUBNET }} netmask {{ MY_NETMASK }}
{
option domain-name-servers {{ MY_DOMAIN_IP }}; 
option domain-name {{ MY_DOMAIN_NAME }}; 
option routers {{ MY_GATEWAY }}; 
option broadcast-address {{ MY_BROADCAST }};

Here is the code I am using:

f = open(DHCPD_PATH, 'w')
g = open(TEMPLATE_PATH, 'r')
patterns = { 
   '{{ MAC_ADDRESS }}'     : mac,
   '{{ IP_ADDRESS }}'      : ip, 
   '{{ MY_IP }}'           : MY_IP,
   '{{ MY_DOMAIN_IP }}'    : MY_DOMAIN_IP,
   '{{ MY_DOMAIN_NAME }}'  : MY_DOMAIN_NAME,
   '{{ MY_NETMASK }}'      : MY_NETMASK,
   '{{ MY_GATEWAY }}'      : MY_GATEWAY,
   '{{ MY_SUBNET }}'       : MY_SUBNET,
   '{{ MY_BROADCAST }}'    : MY_BROADCAST,
}   
content = g.read()
for i,j in patterns.iteritems():
   content = content.replace(i,j)
f.write(content)
f.close()
g.close()

Here is the file I get:

subnet 192.168.10.0 netmask {{ MY_NETMASK }} {}

subnet 192.168.10.0 netmask 255.255.255.0
{
  option domain-name-servers 192.168.10.10;
  option domain-name "localnet.lan";
  option routers 192.168.10.1;
  option broadcast-address 192.168.10.255;
  default-lease-time 600;
  max-lease-time 7200;
  filename "pxelinux.0";
  next-server 192.168.10.3;

I can't understand why is this {{ MY_NETMASK }} remaining whereas one of it has been correctly replaced and every others template-patterns get also correctly replaced.

Can anyone give me a hint on this one? Or at least explain me how to correct it?

Many thanks

like image 460
philippe Avatar asked Dec 12 '22 22:12

philippe


2 Answers

@eumiro guessed right: one of your spaces isn't a space.

>>> repr('subnet {{ MY_SUBNET }} netmask {{ MY_NETMASK }} {}')
"'subnet {{ MY_SUBNET }} netmask {{ MY_NETMASK\\xc2\\xa0}} {}'"
                                              ^^^^^^^^^^

Looks like a non-breaking space.

like image 86
DSM Avatar answered Dec 20 '22 15:12

DSM


Thank you SO much!!

To provide a more complete answer (although yours were clear enough to solve my problem) I would like to provide the vim configuration which would have spared my the pain:

provides different colors for spaces and tabulations:

:set syntax=whitespace

This line in the ~/.vimrc configuration file prints most of invisible characters if you use the :list command once your file is opened (:list! to go back to normal view):

set listchars=nbsp:¤,tab:>-,trail:¤,extends:>,precedes:<,eol:¶,trail:· 

Thanks again

like image 31
philippe Avatar answered Dec 20 '22 15:12

philippe