tags:

views:

173

answers:

5
Q: 

basic grep

I have a large file where each line contains a substring such as ABC123. If I execute

grep ABC file.txt

or

grep ABC1 file.txt

I get those lines back as expected, but if I execute

grep ABC12 file.txt

grep fails to find the corresponding lines.

This seems pretty trivial functionality, but I'm not a heavy user of grep so perhaps I'm missing some gotcha.

A: 

This doesn't make sense. Are you sure the file contains "ABC123"?

You can verify this by running following command in a shell

echo "ABC123" | grep ABC12
Journeyman Programmer
A: 

If the lines contain ABC123, then "grep ABC12" should get them. Do you perhaps mean that you want to match several different strings, such as ABC1, ABC2 and ABC3? In that case you can try this:

grep -E 'ABC1|ABC2|ABC3'
Thomas Padron-McCarthy
A: 

I'm not sure what the problem is.. grep works exactly as it should.. For example, the contents of my test file:

$ cat file.txt
ABC
ABC1
ABC12
ABC123

..and grep'ing for ABC, ABC1, ABC12, ABC123:

$ grep ABC file.txt 
ABC
ABC1
ABC12
ABC123
$ grep ABC1 file.txt 
ABC1
ABC12
ABC123
$ grep ABC12 file.txt 
ABC12
ABC123
$ grep ABC123 file.txt 
ABC123

grep is basically a filter, any line containing the first argument (ABC, or ABC1 etc) will be displayed. If it doesn't contain the entire string, it will not be displayed

dbr
+1  A: 

Is there a chance your file contains some hidden character, such as 0x00 ?

Evert
+3  A: 

Use something like

od -x -a < filename

to dump out the file contents in hex. That'll immediately show you if what you have in your file is what you expect. Which I suspect it isn't :-)

Note: od has lots of useful options to help you here. Too many to list, in fact.

Brian Agnew