tags:

views:

159

answers:

3

Hi,

I try to use grep to match a case like this:

I have a list of hostname and ips in this format:

238-456 192.168.1.1
ak238-456 192.168.1.2
238-456a 192.168.1.3
458-862 192.168.1.4

Now i try to grep "238-456" but of course this returns:

238-456 192.168.1.1

and...

ak238-456 192.168.1.2

and...

238-456a 192.168.1.1

but i only need the line with exactly 238-456. In this case i can't use -x because then of course it returns no results.

Is there a simply way to solve this?

The given answers with "^" solve the first problem. But not the one with the "a" at the end. Can somenone also help with this?

+4  A: 

In this specific example you could search for ^238-456, which only matches when the desired text occurs at the start of the line. For a more general solution, learn about regular expressions (of which this is an example).

edit:

For your new problem, you could simply include a space manually by searching for "^238-456 ". There are also some regexp character classes for spaces. "^238-456\>" should work here. The \> indicates a word boundary, and you probably do need to include the quotes. The other word boundary is \<, so you could change the whole thing to "\<238-456\>" and this would remove the dependency on it being at the start of the line.

kwatford
thanks. works like a charm. but now i found entrys with a "a" at the end. is there also a solution for this?i edited my question.
fwa
Ok, updated with word boundary markers.
kwatford
works perfect. thanks for your time and help :)
fwa
A: 

You can use regular expressions:

egrep "^238-456"

should do, asking to check from the beginning of the line.

An example of tutorial for those regular expression can be found here.

RedGlyph
+1  A: 

use awk

awk '$1=="238-456"' file
ghostdog74