Look for a string on a file and get its line number
Hi,
I have to search for a string on a big file. Once this string is found, I would need to get the number of the line in which the string is located on the file. Do you know how if this is possible to do in python ? Thanks |
What have you tried so far ?
|
What are you getting at ghostdog74 ??? .... :p
Gotta be do-able in python. Me, I'd use perl. |
Quote:
Quote:
|
this is crazy. can some mod/admin help to delete them for me. thanks
|
Well, there is "grep -n", and grep can be called from Python.....
The brute force way (in any language) would be to set up a loop with a line counter and then enclose a command that reads a line and tests for the string. |
Duplicate posts removed.
|
Quote:
Code:
#!/usr/bin/env python |
Hi, thanks for the help. Then I got running the following code;
Code:
#!/usr/bin/env python sdsdsdsdsdsd sdsdsfdgdgdgdg hdfgdgdgdg but instead of this, i get: sdsdsdsdsdsd sdsdsfdgdgdgdg hdfgdgdgdg and also the program is very slow. Do you know how could i solve this ? thanks |
Quote:
|
This is a oneliner in awk:
Code:
awk '/stringOrRegexToFind/ { print NR;}' fileToSearch.txt EDIT: Oops. Didn't notice that this is a python question. |
Quote:
Quote:
|
Quote:
|
Code:
import sys Example: Code:
bash$ python scriptname.py hko /etc/passwd |
Code:
perl -lane 'print "$.:$_" if /text/' file Edit: DOH! just realized it was python question... hmm well since I've already posted I guess I gotta contribute somehow to not look foolish. umm...ooh, regex support! Code:
import sys Edit: changed from re.match() to re.search() |
All times are GMT -5. The time now is 09:59 PM. |