Eric
Eric

Reputation: 167

Python Search String One Liner

I'm trying to use Python a little more and I know this isn't the best use case for it but it's bothering me on why I can't get it to work.

I'm currently using Python 2.7.6 and I want to cat a file and then pull specific strings out of it based on regex. The below code works fine for what I want, but only looks at the first line.

cat /tmp/blah.txt | python -c "import re,sys; m = re.search('Host: (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*OS:(.*) Seq:', sys.stdin.read()); print m.group(1), m.group(2)"

So I assumed I could just use a for loop or fileinput to read the entire file and then put the rest of my code in there but I keep on getting errors with the for loop.

cat /tmp/blah.txt | python -c "import sys; for line in sys.stdin: print line"                                                                                                        File "<string>", line 1
    import sys; for line in sys.stdin: print line
                 ^
SyntaxError: invalid syntax

I've tried a few variations of this but can't get it to work. It always says invalid syntax at the for portion. I know it has to be something very stupid/obvious I'm doing but any help would be appreciated.

If I created a program called arg.py and put the code below in it and call Python via cat, it works fine. It's just the one liner portion that isn't working.

import sys
for line in sys.stdin:
    print line

Upvotes: 1

Views: 440

Answers (1)

Ken4scholars
Ken4scholars

Reputation: 6296

Unfortunately, constructs that introduce indentation in python like if, for among others are not allowed to be preceded by other statements.

Even in your arg.py file try the following:

import sys; for line in sys.stdin: print line

You will discover that the syntax is also invalid which results to the same error.

So, to answer your question, your problem is not the fact that you ran the program in the terminal but the problem is in python syntax itself. It does not support such syntax Check out a related question

Upvotes: 2

Related Questions