Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

finding line number for particular word 1

Status
Not open for further replies.

peac3

Technical User
Jan 17, 2009
226
0
0
AU
Hi guys,

Just wondering how to find the line number for particular word within the file without opening the file because the file contains millions of record.

Thanks,
 
Hi

peac3 said:
Just wondering how to find the line number for particular word within the file without opening the file because the file contains millions of record.
No way. The content of a file can not be examined without reading it. And the content of a file can not be read without opening it.

Anyway, here are some possible ways, test their speed yourself :
Code:
grep -n 'word' /input/file

sed -n '/word/=' /input/file

awk '/word/{print NR}' /input/file

perl -ne 'print"$.\n"if/word/' /input/file

ruby -ne 'puts$.if$_.match(/word/)' /input/file
If you are sure there is only one occurrence of the word, or you are interested only by the first one, you can stop searching after founding one, which can speed up the work :
Code:
grep -n -m 1 'word' /input/file

sed -n '/word/{=;q}' /input/file

awk '/word/{print NR;exit}' /input/file

perl -ne 'if(/word/){print$.;exit}' /input/file

ruby -ne 'if$_.match(/word/):print$.;exit;end' /input/file
Tested with GNU [tt]grep[/tt], GNU [tt]sed[/tt], [tt]gawk[/tt] and [tt]mawk[/tt].

Feherke.
 
Great, Thanks Feherke :)
I'll test them up later which one is faster.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top