Results 1 to 8 of 8

Thread: [SOLVED] Python: search file like grep

  1. #1
    Join Date
    Aug 2006
    Location
    US
    Beans
    1,681

    [SOLVED] Python: search file like grep

    I want to do something like grep with python. I have a file, and I want to search it for a string, and print the line containing that string. Is this possible, and if so, how can I do it?

  2. #2
    Join Date
    Sep 2006
    Beans
    2,914

    Re: Python: search file like grep

    Quote Originally Posted by dbbolton View Post
    I want to do something like grep with python. I have a file, and I want to search it for a string, and print the line containing that string. Is this possible, and if so, how can I do it?
    Code:
    for line in open("file"):
     if "search_string" in line:
       print line
    always read up the documentation and tutorials if you don't know anything.

  3. #3
    Join Date
    Aug 2006
    Location
    US
    Beans
    1,681

    Re: Python: search file like grep

    Quote Originally Posted by ghostdog74 View Post
    Code:
    for line in open("file"):
     if "search_string" in line:
       print line
    always read up the documentation and tutorials if you don't know anything.
    Thanks. I have been reading the docs and a few tutorials, but I got stuck on this one.

    Also, do you know whether it's possible to print only the first occurrence of the search string?

  4. #4
    WW is offline Iced Blended Vanilla Crème Ubuntu
    Join Date
    Oct 2004
    Beans
    1,532

    Re: Python: search file like grep

    Quote Originally Posted by dbbolton View Post
    Also, do you know whether it's possible to print only the first occurrence of the search string?
    Just put a break statement after the print statement.

  5. #5
    Join Date
    Aug 2006
    Location
    US
    Beans
    1,681

    Re: Python: search file like grep

    Thanks

  6. #6
    Join Date
    Apr 2006
    Beans
    147

    Re: [SOLVED] Python: search file like grep

    Another thanks!

  7. #7
    Join Date
    Jul 2009
    Beans
    64
    Distro
    Ubuntu

    Re: [SOLVED] Python: search file like grep

    So I'm doing

    Code:
    for line in open("text.txt"):
     if "ref" in line:
      print line
    And getting back

    Code:
    ref= 1
    (For example)

    All I want displayed is the "1"

    How do I format the output of print line to print just the second part (in bash it would be awk {print $2})

  8. #8
    Join Date
    Sep 2006
    Beans
    2,914

    Re: [SOLVED] Python: search file like grep

    you just need to split .
    Code:
    print line.split("=")[-1]
    i thought you have been reading the docs? split() is very basic for Python string processing.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •