regex - Find nth instance of occurrence of a word in a text file using python -


i using paramiko login device , run commands , capture relevant output. relevant portion of code looks this:

stdin, stdout, stderr = ssh.exec_command('show interface') print stdout.read() 

this gives following output :

ethernet interface 0:0 internet address:     171.182.204.207 netmask 255.255.255.0 internet address:     fe80::2d0:83ff:fe06:4c67 prefixlen 64 mtu size:             1500 link status:          configured full duplex, 1 gigabit/sec network member of bridge: none ethernet interface 0:1 internet address:     fe80::2d0:83ff:fe06:4c66 prefixlen 64 mtu size:             1500 link status:          autosensed full duplex, 1 gigabit/sec network member of bridge: none 

now out of this,i want link status,so did :

stdin, stdout, stderr = ssh.exec_command('show interface') link = '\n'.join(item item in stdout.read().splitlines() if 'link' in item) print link 

and :

link status:          configured full duplex, 1 gigabit/sec network link status:          autosensed full duplex, 1 gigabit/sec network 

works fine.however,what want specify occurrence in list comprehension first,second or nth occurrence of keyword link.

you've 3 options.

store items in list , use indexing. create unnecessary list in memory:

links = [item item in stdout.read().splitlines() if 'link' in item] index = 5 print links[index] 

or use itertools.islice, , pass generator created you've used in code:

from itertools import islice index = 5 links = (item item in stdout.read().splitlines() if 'link' in item) print next(islice(links, index, index+1)) 

or better use itertools.islice following generator. here's not using either .read() or .splitlines() read memory:

links = (item item in stdout if 'link' in item) print next(islice(links, index, index+1)) 

you can use item.startswith('link') in case want match 'link' @ start of string, if want match anywhere in string ignore this.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -