I use Linux. There is a pesky ^M (Windows cariage return) somewhere hidden in thousands of configuration files, and I have to find it, because it makes the server fail.

How do I find ^M among a directories hierarchy full of configuration files?

I think I can not enter ^M on the bash command line. But I have it in a text file that I called m.txt

link|improve this question

71% accept rate
feedback

4 Answers

up vote 10 down vote accepted
grep -r $'\r' *

Use -r for recursive search and $'' for c-style escape in Bash.

More, if you are sure it's text file, then it should be safe to run

cat filename | tr -d $'\r'

to remove all \r in a file. Or you can use sed to do in-place edit, so you won't need to write back.

link|improve this answer
2  
@Nicolas: You can enter a ^M at the command line by pressing ^V^M, but it's better to use $'\r'. – Dennis Williamson Oct 1 '10 at 5:54
Great, it works! Thanks for the ^V^M trick too :-) – Nicolas Raoul Oct 1 '10 at 5:56
feedback

If your server does not have a bash shell, an alternative is to use the -f option on grep, in combination with your prepared m.txt file.

To check your file ...

od -c m.txt
0000000   \r
0000001

To actually do the search

grep -f m.txt *.html *.php *.asp *.whatever

or you can be a little lazy and just type *, but that means that m.txt will be included in the list that comes back.

grep -f m.txt *

The -f filename option on grep is used to specify a file that contains patterns to match, one per line. In this case there's only one pattern.

link|improve this answer
feedback

If you are on a Mac and use homebrew, you can do:

brew install tofrodos
fromdos file.txt

to remove all the Windows carriage returns from file.txt

To switch back to Windows carriage returns,

todos file.txt
link|improve this answer
feedback

In regular expression style, various newlines:

Windows (CR LF)
\r\n

Unix (LF)
\n

Since the \r\n sequence is fairly unique, I think you should be able to search for it that way?

To make things worse Macs used to have just '\r' in place of newline. I cannot verify this, but I don't think MacOSX generations does that any more.

Older Macs (CR)
\r

link|improve this answer
In the directory that contains m.txt, grep "\r\n" * gives no result. No result either for egrep -e "\r\n" * nor grep -E "\r\n" * – Nicolas Raoul Oct 1 '10 at 5:54
@nicolas ah, I misunderstood.. you meant CR only \r my bad. A full windows newline is indeed \r\n or CRLF – Jeff Atwood Oct 1 '10 at 5:58
feedback

Your Answer

 
or
required, but never shown

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