简体   繁体   中英

Strip last period from a host string

I am having a hard time figuring out how to strip the last period from a hostname...

current output:

  • domain.com.
  • suddomain.com.
  • domain.com.
  • subdomain.subdomain.com.
  • subdomain.com.

desired output:

  • domain.com
  • subdomain.com
  • domain.com
  • subdomain.subdomain.com

attempt 1:

print string[:-1]  #it works on some lines but not all

attempt 2:

 str = string.split('.')
 subd = '.'.join(str[0:-1])
 print subd    # does not work at all 

code:

global DOMAINS

if len(DOMAINS) >= 1:
  for domain in DOMAINS:
    cmd = "dig @adonis.dc1.domain.com axfr %s |grep NS |awk '{print $1}'|sort -u |grep -v '^%s.$'" % (domain,domain)
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,   shell=True)
    string = p.stdout.read()
    string = string.strip().replace(' ','')
    if string:
      print string

You do it like this:

hostname.rstrip('.')

where hostname is the string containing the domain name.

>>> 'domain.com'.rstrip('.')
'domain.com'
>>> 'domain.com.'.rstrip('.')
'domain.com'

Regex is:

(.+)\.

The domain without . is now in capture group 1.

The answer given by @isedev is somewhat incomplete in this specific use case. rstrip('.') will strip the trailing period from a string, however the string returned by subprocess will have a trailing newline character (0x0A) following the period which causes rstrip('.') to fail.

This is likely why OP gave up.

Consider the following python3 code:

print ('domain.'.rstrip('.'))

Works as perceived. However, adding a newline character to mimic shell output:

print ('domain.\n'.rstrip('.'))

prints domain.

One way to manage this is to simply insert a strip() before the rstrip() call:

print ('domain.\n'.strip().rstrip('.'))

which prints: domain

Always, always strip your shell output:)

我放弃了,只是用 sed 代替....

cmd = "dig @adonis.dc1.domain.com axfr %s |grep NS |awk '{print $1}' |sort -u |grep -v '^%s.$'|sed -e 's/.$//'"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM