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!

Search a file for a key word using grep

Status
Not open for further replies.

buxtonicer1

Programmer
Sep 20, 2006
82
GB
Hi,
Is it possible to search a file for a key word or a line that contains a key word. I know you can use the grep option but how do you invoke an exact match. I only want an exact match to return. However, it does seem straight forward though. As always with UNIX, the learning curve is steep.
 
You could use the -v option to exclude whatever spurious matches you wish:

grep word filename | grep -v 'exclusion' | grep -v 'exclusion' and so on.

 
If you mean how do you include 'text' but exclude, for example, 'context' then that's a little more complex. A starting point is to use
Code:
grep " text " filename
but, and it's a big but, this will miss the word text when
[ol]
[li]It's at the beginning of a line[/li]
[li]It's at the end of a line[/li]
[li]It's at the end of a sentence[/li]
[li]It's in quotes[/li]
[li]It's got a tab in front of it or behind it[/li]
[li]There are plenty more exceptions but I'm sure you're getting the point[/li]
[/ol]
If you really want/need to do this you need to reach for a more powerful tool such as awk or perl. The code
Code:
perl -e 'while (<>){/\btext\b/ and print;}' filename
would do the trick but perl - and awk - are whole separate subjects of their own.

Ceci n'est pas une signature
Columb Healy
 
Hi

For example my [tt]grep[/tt] can handle it.
man grep said:
-w, --word-regexp
Select only those lines containing matches that
form whole words. The test is that the matching
substring must either be at the beginning of the
line, or preceded by a non-word constituent charac-­
ter. Similarly, it must be either at the end of
the line or followed by a non-word constituent
character. Word-constituent characters are let-­
ters, digits, and the underscore.
It is GNU [tt]grep[/tt] 2.5.1.

Feherke.
 
Hi

By the way, some [tt]grep[/tt]s can match the boundary like in your [tt]perl[/tt] code :
Code:
grep '\b[green][i]text[/i][/green]\b' /input/file
Or can do a messy somehow equivalent :
Code:
grep '\([^[:alnum:]_]\|^\)[green][i]text[/i][/green]\([^[:alnum:]_]\|$\)' /input/file

[gray]# or[/gray]

grep -E '([^[:alnum:]_]|^)[green][i]text[/i][/green]([^[:alnum:]_]|$)' /input/file
By the way, you have a [tt]while[/tt] in your [tt]perl[/tt] code which could be done automatically by the interpreter :
Code:
perl -ne 'print if /\b[green][i]text[/i][/green]\b/' /input/file

[gray]# or[/gray]

perl -pe '/\b[green][i]text[/i][/green]\b/||($_="")' /input/file

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top