现需求是读入A文件和B文件,将A文件中某段文字换成,B文件中的内容,保存A文件。
读入A、B文件没问题,但是如何在A文件中找出对应的位置,并将其换成B文件呢?
文件格式如下
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
# Modified hosts start
..... 此处为更换内容!
# Modified hosts end
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
换个思路!
将hosts文件读入后使用 .split('# Modified hosts start') 将文件分割成数组两部分,第一部分保存原有hosts文件的头部;
将抓取来的文件也通过这种方式分割,将第二部分即为要更换的内容;
将1、2步的内容合并后写入hosts问即可!
写一个正则匹配一下