简体   繁体   中英

I need to get specific data from text file in python

I have Some information in a string output which i am getting from

subprocess.Popen(['/bin/grep', '-E', 'CLIENTS', p ], stdout=subprocess.PIPE, encoding='utf-8')

when i print i am getting like below

CLIENTS='ip-10-161-110-51:ip-10-161-111-52:ip-10-161-112-53'
ISCSI_CLIENTS='ip-10-161-110-51,ip-10-161-111-52-227,ip-10-161-112-53'
NFS_CLIENTS='ip-10-161-110-51,ip-10-161-111-52,ip-10-161-112-53'
CLIENTS='ip-10-161-110-43:ip-10-161-111-42:ip-10-161-112-41'
ISCSI_CLIENTS='ip-10-151-108-51,ip-11-161-111-42,ip-10-161-112-41'
NFS_CLIENTS='ip-10-121-110-32,ip-10-161-111-34,ip-10-161-112-35'

How can i merge this to get the output as below

CLIENTS = ip-10-161-110-51:ip-10-161-111-52:ip-10-161-112-53:ip-10-161-110-43:ip-10-161-111-42:ip-10-161-112-41
NFS_CLIENTS = ip-10-161-110-51,ip-10-161-111-52,ip-10-161-112-53,ip-10-151-108-51,ip-11-161-111-42,ip-10-161-112-41
ISCSI_CLIENTS = ip-10-161-110-51,ip-10-161-111-52-227,ip-10-161-112-53,ip-10-151-108-51,ip-11-161-111-42,ip-10-161-112-41

Try using find on a string in python to get start and stop locations of wanted text in the string. You can then call that bit of the string out of the array like this.

    input_text = ""
    text_start = input_text.find("NODES")
    text_stop = input_text[text_start].find("# The") + text_start
    wanted_text = input_text[text_start:text_stop]
    print(wanted_text)

You can expand on this idea to find the exact starting locations by name such as "NODES" or "FILERA=ip" then search for an end character such as a ',' after to get each item separate from one another. I have made the code above grab the wanted batch of text that was given, you just need to feed the file output into where input_text is located in the code to set it up dynamically.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM