Searching in files

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Andu
    New Member
    • Apr 2007
    • 8

    Searching in files

    Ok, i'm using Linux Ubuntu, running on kernel 2.6.15-23 and i am writing a program in python that has to do with memory.

    I need to open the file System.map-2.6.15-23-386 which i managed to do.

    Code:
    sysmap=open('/boot/System.map-2.6.15-23-386','r')
    Now my problem lies with the following.. I need it to search for an entry in this file. If i were using the terminal, what i would do is use the following command

    Code:
    cat /boot/System.map-2.6.15-23-386-default | grep init_task
    (this basically outputs the instances in the system.map file where init_task appears, together with the address.

    I'm not entirely sure how to implement this command in python.

    Also, after i do that, i need to grab part of the file (which i can do using the .read command) and look for a similar string in another binary file. ...again.. i'm not too sure as to how to go around this..

    Can anyone help please?
  • dshimer
    Recognized Expert New Member
    • Dec 2006
    • 136

    #2
    Using a different file and piece of text (which occur on my system) here is an example that returns the position of the string in the file as a place to start.
    Code:
    >>> open('/tmp/ipscan.txt','r').read().find('SCAN')
    541
    if you are going to keep looking for other strings, or are going to need the data for other purposes it may be better to read the whole file into a string variable, get the address then slice the string based on what you need to do.

    Comment

    • ghostdog74
      Recognized Expert Contributor
      • Apr 2006
      • 511

      #3
      1) Line by line search
      Code:
      for line in open("yourfile_tosearch"):
          if "string" in line:
              print line.strip()
      2) using regular expression
      Code:
      import re
      data = open("yourfile_tosearch").read()
      print re.findall("string", data)

      Comment

      • Andu
        New Member
        • Apr 2007
        • 8

        #4
        Ok, i uses a line by line search, that solved my problem. Thanks for your help :)

        Comment

        Working...