Ask Different is a question and answer site for power users of Apple hardware and software. 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

When I run grep on a text file, I get nonsense results. It seems as if the whole file is printed out but on one line overwriting itself. I read that on the Mac, text files use \r instead of the normal \n as a line ending. That would explain it, but how to make grep treat \r as if it were \n?

I'm using Snow Leopard OS X, and am quite new to using Apple anything, but a long-time Linux programmer.

share|improve this question
up vote 8 down vote accepted

You can't change grep's behavior, but you can change the file it sees:

tr '\r' '\n' <file | grep foo

Also, \r line endings are legacy these days; OS X officially uses \n, although there are still things that haven't been updated. In particular, AppleScript still hasn't quite caught up, which also shows in its using pre-OS X file paths by default and requiring POSIX file to indicate OS X native paths; also, many Carbon applications still use \r, Carbon being a transition framework from Mac OS 9 to OS X.

share|improve this answer
Good to know \n is 'in' now. So I just need to convert the few existing files with \r to use \n. – DarenW Jun 29 '11 at 17:20
Your answer has also doubled my knowledge of what "Carbon" is! – DarenW Jun 29 '11 at 17:21
If you don't want to actually change the content of the source files themselves, this answer is better as it does the translation in-stream rather than hack the original file. Nice! – Viktor Haag Jun 29 '11 at 17:34
I wonder if it would be wise to create an alias for grep that includes the tr piece? – DarenW Jul 5 '11 at 16:43
That's up to you; aliases are per user. If you need it a lot then it's probably worthwhile. – geekosaur Jul 5 '11 at 16:47

A common legacy utility for handling line endings is flip. It does in-place transformation for files between Unix, DOS/Windows, legacy Mac line-end formats, and can also sample a file to let you know what type it currently thinks it is. It doesn't ship with OSX, but you can get binaries from the link as well as source.

In this case, you can first flip -u yourFile.txt to make sure it's using newlines and not linefeeds to demarcate lines, and then use grep on it.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.