Hello, I currently have the following python code:

#usr/bin/python
import os

variable=raw_input('Search for this string: ')
os.system("grep $variable sample.txt")

Basically what I want to do is to grep a string found in the text file "sample.txt" When I run the code, it just hangs. How can I make it so that grep accepts the variable?

Edited 6 Years Ago by jl487: n/a

first: Why shell out to the system to get pattern matching when python offers the re package?
second: call it like this:

os.system("grep %s sample.txt"%variable)

And you have to supply the path unless sample.txt is in your PYTHONPATH.

os.system("grep %s ./sample.txt" % variable)  ## current directory

griswolf, thank you so much. However, how can I make it so it searches for an exact phrase (you vs. you're).

Also, I am unfamiliar with the re package. Looks like i'll have to run a google search.

I would do the search myself as for me Python is more powerful in many cases as regular expression language, which is like code language.

How ever, as they say: "Somebody likes the daughter, somebody else the mother."

Here my 5 minute code with text from above link of re documentation:

filename="sample.txt"
variable=raw_input('Search for this string: ').lower()

res= [line for line in open(filename) if variable in line.lower()]

for i in res:
      print i,
      print '-'*20
""" Output: (text file from re module documentation)
Search for this string: re.match
>>> re.match("c", "abcdef")  # No match
--------------------
    result = re.match(pattern, string)
--------------------
    The compiled versions of the most recent patterns passed to re.match(), re.search() or re.compile() are cached, so programs that use only a few regular expressions at a time needn?t worry about compiling regular expressions.
--------------------
re.match(pattern, string[, flags])¶
--------------------
class re.MatchObject¶
--------------------
        >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
--------------------
        >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
--------------------
        >>> m = re.match(r"(..)+", "a1b2c3")  # Matches 3 times.
--------------------
        >>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
--------------------
        >>> m = re.match(r"(\d+)\.?(\d+)?", "24")
--------------------
        >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
--------------------
# Error because re.match() returns None, which doesn't have a group() method:
--------------------
    re.match(r".*(.).*\1", "718ak").group(1)
--------------------
>>> re.match('Begin (\w| )*? end', s).end()
--------------------
>>> re.match("o", "dog")  # No match as "o" is not the first letter of "dog".
--------------------
The following applies only to regular expression objects like those created with re.compile("pattern"), not the primitives re.match(pattern, string) or re.search(pattern, string).
--------------------
>>> re.match(r"\W(.)\1\W", " ff ")
--------------------
>>> re.match("\\W(.)\\1\\W", " ff ")
--------------------
>>> re.match(r"\\", r"\\")
--------------------
>>> re.match("\\\\", r"\\")
--------------------
>>> """

Edited 6 Years Ago by pyTony: Added sample.txt

Attachments
7.2. re ? Regular expression operations

This module provides regular expression matching operations similar to those found in Perl. Both patterns and strings to be searched can be Unicode strings as well as 8-bit strings.

Regular expressions use the backslash character ('\') to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides with Python?s usage of the same character for the same purpose in string literals; for example, to match a literal backslash, one might have to write '\\\\' as the pattern string, because the regular expression must be \\, and each backslash must be expressed as \\ inside a regular Python string literal.

The solution is to use Python?s raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with 'r'. So r"\n" is a two-character string containing '\' and 'n', while "\n" is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation.

It is important to note that most regular expression operations are available as module-level functions and RegexObject methods. The functions are shortcuts that don?t require you to compile a regex object first, but miss some fine-tuning parameters.

See also

Mastering Regular Expressions
    Book on regular expressions by Jeffrey Friedl, published by O?Reilly. The second edition of the book no longer covers Python at all, but the first edition covered writing good regular expression patterns in great detail.

7.2.1. Regular Expression Syntax

A regular expression (or RE) specifies a set of strings that matches it; the functions in this module let you check if a particular string matches a given regular expression (or if a given regular expression matches a particular string, which comes down to the same thing).

Regular expressions can be concatenated to form new regular expressions; if A and B are both regular expressions, then AB is also a regular expression. In general, if a string p matches A and another string q matches B, the string pq will match AB. This holds unless A or B contain low precedence operations; boundary conditions between A and B; or have numbered group references. Thus, complex expressions can easily be constructed from simpler primitive expressions like the ones described here. For details of the theory and implementation of regular expressions, consult the Friedl book referenced above, or almost any textbook about compiler construction.

A brief explanation of the format of regular expressions follows. For further information and a gentler presentation, consult the Regular Expression HOWTO.

Regular expressions can contain both special and ordinary characters. Most ordinary characters, like 'A', 'a', or '0', are the simplest regular expressions; they simply match themselves. You can concatenate ordinary characters, so last matches the string 'last'. (In the rest of this section, we?ll write RE?s in this special style, usually without quotes, and strings to be matched 'in single quotes'.)

Some characters, like '|' or '(', are special. Special characters either stand for classes of ordinary characters, or affect how the regular expressions around them are interpreted. Regular expression pattern strings may not contain null bytes, but can specify the null byte using the \number notation, e.g., '\x00'.

The special characters are:

'.'
    (Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline.
'^'
    (Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.
'$'
    Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline. foo matches both ?foo? and ?foobar?, while the regular expression foo$ matches only ?foo?. More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches ?foo2? normally, but ?foo1? in MULTILINE mode; searching for a single $ in 'foo\n' will find two (empty) matches: one just before the newline, and one at the end of the string.
'*'
    Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match ?a?, ?ab?, or ?a? followed by any number of ?b?s.
'+'
    Causes the resulting RE to match 1 or more repetitions of the preceding RE. ab+ will match ?a? followed by any non-zero number of ?b?s; it will not match just ?a?.
'?'
    Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either ?a? or ?ab?.
*?, +?, ??
    The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn?t desired; if the RE <.*> is matched against '<H1>title</H1>', it will match the entire string, and not just '<H1>'. Adding '?' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '<H1>'.
{m}
    Specifies that exactly m copies of the previous RE should be matched; fewer matches cause the entire RE not to match. For example, a{6} will match exactly six 'a' characters, but not five.
{m,n}
    Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 'a' characters. Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an example, a{4,}b will match aaaab or a thousand 'a' characters followed by a b, but not aaab. The comma may not be omitted or the modifier would be confused with the previously described form.
{m,n}?
    Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as few repetitions as possible. This is the non-greedy version of the previous qualifier. For example, on the 6-character string 'aaaaaa', a{3,5} will match 5 'a' characters, while a{3,5}? will only match 3 characters.
'\'

    Either escapes special characters (permitting you to match characters like '*', '?', and so forth), or signals a special sequence; special sequences are discussed below.

    If you?re not using a raw string to express the pattern, remember that Python also uses the backslash as an escape sequence in string literals; if the escape sequence isn?t recognized by Python?s parser, the backslash and subsequent character are included in the resulting string. However, if Python would recognize the resulting sequence, the backslash should be repeated twice. This is complicated and hard to understand, so it?s highly recommended that you use raw strings for all but the simplest expressions.
[]

    Used to indicate a set of characters. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a '-'. Special characters are not active inside sets. For example, [akm$] will match any of the characters 'a', 'k', 'm', or '$'; [a-z] will match any lowercase letter, and [a-zA-Z0-9] matches any letter or digit. Character classes such as \w or \S (defined below) are also acceptable inside a range, although the characters they match depends on whether LOCALE or UNICODE mode is in force. If you want to include a ']' or a '-' inside a set, precede it with a backslash, or place it as the first character. The pattern []] will match ']', for example.

    You can match the characters not within a range by complementing the set. This is indicated by including a '^' as the first character of the set; '^' elsewhere will simply match the '^' character. For example, [^5] will match any character except '5', and [^^] will match any character except '^'.

    Note that inside [] the special forms and special characters lose their meanings and only the syntaxes described here are valid. For example, +, *, (, ), and so on are treated as literals inside [], and backreferences cannot be used inside [].
'|'
    A|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the '|' in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by '|' are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the '|' operator is never greedy. To match a literal '|', use \|, or enclose it inside a character class, as in [|].
(...)
    Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special sequence, described below. To match the literals '(' or ')', use \( or \), or enclose them inside a character class: [(] [)].
(?...)
    This is an extension notation (a '?' following a '(' is not meaningful otherwise). The first character after the '?' determines what the meaning and further syntax of the construct is. Extensions usually do not create a new group; (?P<name>...) is the only exception to this rule. Following are the currently supported extensions.
(?iLmsux)

    (One or more letters from the set 'i', 'L', 'm', 's', 'u', 'x'.) The group matches the empty string; the letters set the corresponding flags: re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), re.U (Unicode dependent), and re.X (verbose), for the entire regular expression. (The flags are described in Module Contents.) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the re.compile() function.

    Note that the (?x) flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, t
This article has been dead for over six months. Start a new discussion instead.