![](/img/trans.png)
[英]Regex to filter and remove specific multiple lines of text from a file with python
[英]How to remove multiple lines in a text file using regex in python?
我想使用正則表達式刪除文件中的多行。
我有一個像這樣的文件:
host host_name {
# comment (optional)
hardware ethernet 01:22:85:EA:A8:5D;
fixed-address 192.168.107.210;
}
host another_host_name {
# comment (optional)
hardware ethernet 01:22:85:EA:A8:5D;
fixed-address 192.168.107.210;
}
基本上,當我選擇主機名(例如host_name
,它將檢測到具有該主機名的行並刪除其后的所有行,直到遇到第一個{
為止:
#before
host host_name {
# comment (optional)
hardware ethernet 01:22:85:EA:A8:5D;
fixed-address 192.168.107.210;
}
host another_host_name {
# comment (optional)
hardware ethernet 01:22:85:EA:A8:5D;
fixed-address 192.168.107.210;
}
#after
host another_host_name {
# comment (optional)
hardware ethernet 01:22:85:EA:A8:5D;
fixed-address 192.168.107.210;
}
我猜我們會使用m = search('r"^host.*}', line)
之類的東西m = search('r"^host.*}', line)
但它適用於逐行的東西,而不適用於多行。
def remove(filename, hostname):
with open(os.path.abspath("app/static/DATA/{}".format(filename)), "a") as f:
for line in f:
m = search('r"^hostname.*}', line, re.MULTILIGNE)
if m:
#we delete the bloc, I don't know how to do it though
這樣開始嗎?
我有3個想法給您。
嘗試多線模式。 您可以在這里閱讀有關它的更多信息: https : //docs.python.org/3/library/re.html#re.MULTILINE ,我認為它將滿足您的要求。
如果那不能解決問題,我就會作弊。 我將運行一個正則表達式前,將所有\\ n交換為諸如“ this_is_my_special_holder”之類的奇怪內容。 現在一切都在一條線上。 我會像你寫的那樣去做我想要的工作。 然后,我將運行一個后正則表達式,將所有“ this_is_my_special_holder”交換回\\ n。 如果您曾經遇到不支持多行的語言,那么應該總是把它完成:)
您可能只能夠運行正則表達式,這里的示例就是這樣:
這是我將要完成的全部操作:import re
def main(regex_part):
the_regex = re.compile("".join(["host ", regex_part, " {[^}]+}"]))
with open('test.txt', 'r') as myfile:
data=myfile.read()
data = re.sub(the_regex, "", data)
print (data)
with open('test2.txt', 'w') as newfile:
newfile.write(data)
main("host_name")
我用“ with”打開文件,這樣您以后就不必關閉文件句柄了。 “ r”是讀取文件,“ w”是寫入文件。 正則表達式僅替換:
host host_name { everything up to the next } and then the next }
一無所有。
http://regex101.com是實際使用正則表達式的便捷站點。 祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.