擅长:python、mysql、java
<p>如果已经有行列表,只需从要删除的行之前和之后的零件创建一个新的更新列表:</p>
<pre><code>import re
with open('data.txt') as f:
s = f.read()
print("Before:")
print(s)
def delete_host(s):
host = raw_input('Please enter host you would like to delete: ')
lines = s.split('\n')
for i, line in enumerate(lines):
if re.match(r'\s*host\s+' + host + '\s*{', line):
break
for j, line in enumerate(lines[i+1:]):
if re.match(r'\s*}', line):
break
j = i + j + 1
new_lines = lines[:i] + lines[j+1:]
return '\n'.join(new_lines)
s = delete_host(s)
print("After:")
print(s)
</code></pre>
<p>(请注意,检查缺少的主机名、格式不正确的主机名或带有可能干扰regexp的有趣符号的主机名时不会出错)。你知道吗</p>
<p>如果您确定所有的条目总是像您描述的那样(特别是,<code>}</code>不会在<code>host</code>正文的任何地方遇到),您可以将其简化为</p>
<pre><code>def delete_host(s):
host = raw_input('Please enter host you would like to delete: ')
return re.sub(r'\s*host\s+' + host + '\s*{[^}]*}', '', s, flags=re.MULTILINE)
</code></pre>
<p>最安全的方法是实际解析配置文件,获取数据结构,删除条目,然后创建一个新的配置文件。你知道吗</p>