Grepping words for match in a file

Dan Sommers 2QdxY4RzWzUUiLuE at potatochowder.com
Sat Dec 28 11:05:57 EST 2019


On 12/28/19 12:29 AM, Mahmood Naderan via Python-list wrote:
> Hi
> I have some lines in a text file like
> ADD R1, R2
> ADD3 R4, R5, R6
> ADD.MOV R1, R2, [0x10]
> If I grep words with this code
> for line in fp:
>      if my_word in line:
> Then if my_word is "ADD", I get 3 matches. However, if I grep word with this code
> for line in fp:
>      for word in line.split():
>          if my_word == word:
> Then I get only one match which is ADD R1. R2.
> Actually I want to get 2 matches. ADD R1, R2 and ADD.MOV R1, R2, [0x10] because these two lines are actually "ADD" instructions. However, "ADD3" is something else.
> How can I fix the code for that purpose?

Grep's "words" are different from what line.split() returns:

     >>> 'ADD.MOV R1, R2, [0x10]'.split()
     ['ADD.MOV', 'R1,', 'R2,', '[0x10]']

If you want to match "ADD" instructions, you'll have to use
word.startswith or some other method to separate the "ADD"
from the ".MOV."

Dan


More information about the Python-list mailing list