0

I have a text file and looking for the single line bird. Using OS X Lion and grep 2.5.1.

this works:

grep '^bird' file.txt

but this doesn't

grep '^bird$' file.txt

There is not a blank space at the end of the line. What am I doing wrong?

thx

migrated from serverfault.com Jan 18 '12 at 22:05

This question came from our site for system and network administrators.

  • Works for me. Just one very long shot: You search enable1.txt in variant 1 and file.txt in variant 2. – Sven Jan 18 '12 at 18:58
  • looks like CRLF updated to file.txt – timpone Jan 18 '12 at 19:20
5

Its usually because of a DOS formatted text file (CRLF). To clean the file you can install a tooö like dos2unix; but usually works even simpler by using the tr tool:

tr -d '\r' < testfile > output.txt
  • Agreed, that should work pretty much anywhere. – rjewell Jan 18 '12 at 20:34
4

I'm guessing it's a CRLF file (dos formatted text file)

[bob@erasmas tmp]$ cat testfile
bird
notbird
[bob@erasmas tmp]$ cat testfile.dos
bird
notbird
[bob@erasmas tmp]$ file testfile
testfile: ASCII text
[bob@erasmas tmp]$ file testfile.dos
testfile.dos: ASCII text, with CRLF line terminators
[bob@erasmas tmp]$ grep '^bird' testfile
bird
[bob@erasmas tmp]$ grep '^bird' testfile.dos
bird
[bob@erasmas tmp]$ grep '^bird$' testfile
bird
[bob@erasmas tmp]$ grep '^bird$' testfile.dos

Note: This was on a Linux machine, as this is not specific to OS X (if this is infact the problem).

Run "file" on file.txt and see if it has CRLF line endings.

  • this is corect. file.txt: ASCII c program text, with CRLF line terminators - any idea how to check. seems like grep should handle this... – timpone Jan 18 '12 at 19:19
  • looks like this did it sed 's/.$//' file.txt > fixed.txt – timpone Jan 18 '12 at 19:33
  • 2
    That sed statement removes ANY character at the end of a line, which might unintentionally clean away too much if you're unlucky. But as always with *NIX; loads of way to do the same thing. See my answer below for another way to clean it up. :) – Mattias Ahnberg Jan 18 '12 at 19:38
1

If you want to keep the MS-DOS formatting, then you can insert the MS-DOS carriage return within the pattern. On linux I press CTRL-V CTRL-M to produce the literal ^M representing the MS-DOS CR (sometimes noted as \r). Hope on OS X you will find how to produce the literal CR.

grep --color=none "^bird^M$"

You must log in to answer this question.

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