Adding short-hostname into the /etc/hosts file with python
Question: Currently my /etc/hosts file is missing the short-hostname(last column) is
there a way to take the FQDN value in the file remove '.pdp.wdf.ltd' and add
the hostname to the last column. To reach till here I did write a small python
script wrote it to a file, but unable to proceed to get the short-hostname
added

    
    
    #!/usr/bin/env python
    import re,subprocess,os,socket
    a=subprocess.Popen('ifconfig -a', stdout=subprocess.PIPE, shell=True)
    _a, err= a.communicate()
    _ou=dict(re.findall(r'^(\S+).*?inet addr:(\S+)', _a, re.S | re.M))
    _ou=_ou.values()
    _ou.remove('127.0.0.1')
    
    y=[]
    for i in _ou:
        _z = '{0} ' .format (i), socket.getfqdn(i)
        y.append(_z)
    
    _y=dict(y)
    _z=(' \n'.join('{0} \t {1}'.format(key, val)for (key,val) in _y.iteritems()))
    

# cat /etc/hosts

    
    
    #IP-Address      Full-Qualified-Hostname        Short-Hostname
    10.68.80.28      dewdfgld00035.pdp.wdf.ltd      
    10.68.80.45      lddbrdb.pdp.wdf.ltd            
    10.68.80.46      ldcirdb.pdp.wdf.ltd            
    10.72.176.28     dewdfgfd00035b.pdp.wdf.ltd  
    

**Output needed in the /etc/hosts file**

    
    
    ##IP-Address      Full-Qualified-Hostname       Short-Hostname
    10.68.80.28      dewdfgld00035.pdp.wdf.ltd      dewdfgld00035
    10.68.80.45      lddbrdb.pdp.wdf.ltd            lddbrdb
    10.68.80.46      ldcirdb.pdp.wdf.ltd            ldcirbd
    10.72.176.28     dewdfgfd00035b.pdp.wdf.ltd     dewdfgfd00035b
    


Answer: You can use the following to match (with `g`lobal and `m`ultiline flags) :

    
    
    (^[^\s#]+\s+([^.\n]+).*)
    

And replace with the following:

    
    
    \1\2
    

See [RegEX DEMO](https://regex101.com/r/cP2fA1/1)

