Jul-01-2019, 12:15 AM
Hi,
New to this site and to python. As a first project, I am trying to extract entire line entries via regex from a text file (hosts.txt). Based on matches, I want to include those matches into ini-type sections of a flat text file, 'final_host'. So I am trying to put 'cars' matches under [cars], 'trucks' matches under [trucks], etc.
Here is an example hosts.txt file:
car1
car2
truck1
truck12
truck13
Here is my code:
But all I'm getting for results are the ini headers. Is there an easier way to regex?
[car]
[truck]
OS: Ubuntu
Python: 2.7.15
Thank you in advance for any pointers.
New to this site and to python. As a first project, I am trying to extract entire line entries via regex from a text file (hosts.txt). Based on matches, I want to include those matches into ini-type sections of a flat text file, 'final_host'. So I am trying to put 'cars' matches under [cars], 'trucks' matches under [trucks], etc.
Here is an example hosts.txt file:
car1
car2
truck1
truck12
truck13
Here is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import re source = open ( "hosts" , "r" ) car = re. compile ( ".*car\S+" ) truck = re. compile ( ".*truck\S+" ) for line in source: car_result = car.findall(line) truck_result = truck.findall(line) source.close() with open ( 'final_host' , 'w' ) as y: y.write( "[car]\n" ) for x in car_result: print (x) y.write( "[truck]\n" ) for x in truck_result: print (x) y.close() |
[car]
[truck]
OS: Ubuntu
Python: 2.7.15
Thank you in advance for any pointers.