Why does grep need a dot in a regex using ‘$’

grepregex

I though I knew grep, but maybe not.

I want to find all lines in a file ending with ':' If I run

grep :$ ~/greptester.txt

but to my surprise, it gives no results. Sometimes I confuse '^' and '$', having to guess which is begin and which is end of line, but I checked and $ is indeed the end of a line.

After much screwing around, I accidently discovered that running

grep :.$ ~/greptester.txt

does give the expected results. Why?

Here is the text file:

test line one
1 line with a colon:
ignore this line
3456 some stuff:
cat: meow; dog: bark; horse: four (4) legs.
goat, 7 elephants

This happens both on Ubuntu and on a Windows machine with Cygwin.

Best Answer

Your file has \r\n (CR+LF) line endings (likely, created in windows?), whereas most UNIX files only end in \n (LF).

So, before grep sees the \n after the : character, there is the \r that it has to match with the . wildcard.

Related Question