Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
As Kent brilliantly deduced, yes, the text file was written on Windows. – DarenW Sep 17 '13 at 4:12
Don't forget to single-quote your patterns. Better be safe than sorry when there's chance for an expansion happening. – slhck Sep 17 '13 at 5:33
up vote 6 down vote accepted

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.

share|improve this answer
It's 2013 and we're still dealing with line ending nonsense. Humans, sheesh! Follow up question: why not make grep smart enough to ignore this detail? – DarenW Sep 17 '13 at 0:37
You might check the version of grep you're using. In OSX, the default is to strip the CR characters, so it behaves as you would expect (:$ would match). It also has the option -U to not strip the CR, which is how your version apparently behaves by default. – Kent Sep 17 '13 at 0:48
@darenw because \r is a real character and sometimes you may want to search for it (it's happened to me). Having grep arbitrarily decide that \r is somehow special is a BAD idea. What should it do with \t or any other escape character? – terdon Sep 17 '13 at 1:17
@terdon Unless \r is followed by \n, in which case you, most likely, want to ingore \r and treat the entire sequence \r\n as one character — line end. – Alexey Ivanov Sep 17 '13 at 5:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .