[英]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.