I want to check if a string is matching a substring in a line after 3rd occurrence of delimiter
mapping_name
= reversed
delimiter
= #
Contents of test_file.txt
1#ABC#test#reversed_once#gm#999
2#WBC#test_1#reversed_first#gm#9998
3#TBC#tested#reversed_last#gm#9998
4#CBC#test#reversed_reversed#gm#999
5#ZBC#test#reversed#gm#9990
I have done like below
wf_string = []
batch_file = open("/home/tester/test_file.txt", 'r')
for lines in batch_file:
if mapping_name in lines:
print(lines)
wf_string.append(lines)
But it is printing lines 4 and 5
. Ideally it should print only the 5th
line
Try something like the below ( Note that the code assume that you want to natch against fourth field only)
match = 'reversed'
with open('in.txt') as f:
for idx,line in enumerate(f,1):
if match == line.split('#')[3]:
print(f'match in line {idx}')
output
match in line 5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.