[英]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:当前 output:
desired output:所需的 output:
attempt 1:尝试1:
print string[:-1] #it works on some lines but not all
attempt 2:尝试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.其中 hostname 是包含域名的字符串。
>>> 'domain.com'.rstrip('.')
'domain.com'
>>> 'domain.com.'.rstrip('.')
'domain.com'
Regex is: 正则表达式是:
(.+)\.
The domain without .
域没有
.
is now in capture group 1. 现在处于捕获组1中。
The answer given by @isedev is somewhat incomplete in this specific use case.在这个特定的用例中,@isedev 给出的答案有些不完整。
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. rstrip('.')
将从字符串中删除尾随句点,但是subprocess
进程返回的字符串将在导致rstrip('.')
失败的句点后面有一个尾随换行符 (0x0A)。
This is likely why OP gave up.这可能是 OP 放弃的原因。
Consider the following python3 code:考虑以下 python3 代码:
print ('domain.'.rstrip('.'))
Works as perceived.按感知工作。 However, adding a newline character to mimic shell output:
但是,添加一个换行符来模仿 shell output:
print ('domain.\n'.rstrip('.'))
prints domain.
打印
domain.
One way to manage this is to simply insert a strip()
before the rstrip()
call:一种管理方法是在
rstrip()
调用之前简单地插入一个strip()
:
print ('domain.\n'.strip().rstrip('.'))
which prints: domain
打印:
domain
Always, always strip your shell output:)始终,始终剥离您的 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.