[英]Strip last period from a host string
我很难弄清楚如何从主机名中删除最后一个句点......
当前 output:
所需的 output:
尝试1:
print string[:-1] #it works on some lines but not all
尝试2:
str = string.split('.')
subd = '.'.join(str[0:-1])
print subd # does not work at all
代码:
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
你这样做:
hostname.rstrip('.')
其中 hostname 是包含域名的字符串。
>>> 'domain.com'.rstrip('.')
'domain.com'
>>> 'domain.com.'.rstrip('.')
'domain.com'
正则表达式是:
(.+)\.
域没有.
现在处于捕获组1中。
在这个特定的用例中,@isedev 给出的答案有些不完整。 rstrip('.')
将从字符串中删除尾随句点,但是subprocess
进程返回的字符串将在导致rstrip('.')
失败的句点后面有一个尾随换行符 (0x0A)。
这可能是 OP 放弃的原因。
考虑以下 python3 代码:
print ('domain.'.rstrip('.'))
按感知工作。 但是,添加一个换行符来模仿 shell output:
print ('domain.\n'.rstrip('.'))
打印domain.
一种管理方法是在rstrip()
调用之前简单地插入一个strip()
:
print ('domain.\n'.strip().rstrip('.'))
打印: domain
始终,始终剥离您的 shell output :)
我放弃了,只是用 sed 代替....
cmd = "dig @adonis.dc1.domain.com axfr %s |grep NS |awk '{print $1}' |sort -u |grep -v '^%s.$'|sed -e 's/.$//'"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.