Search code examples
phpbashreplaceline-endingsnewline

I need way to find all files containing odd ^M invisible characters


I know for a fact that these PHP files exist. I can open them in VIM and see the offending character.

I found several links here on stackoverflow that suggest remedies for this but none of them work properly. I know for a fact that several files do not contain the ^M characters (CRLF line endings) however, I keep getting false positives.

find . -type f -name "*.php" -exec fgrep -l $'\r' "{}" \;

Returns false positives.

find . -not -type d -name "*.php" -exec file "{}" ";" | grep CRLF

Returns nothing.

etc...etc...

Edit: Yes, I am executing these lines in the offending directory.


Solution

  • Do you use a source control repository for storing your files? Many of them have the ability to automatically make sure that line endings of files are correct upon commit. I can give you an example with Subversion.

    I have a pre-commit hook that allows me to specify what properties in Subversion must be on what files in order for those files to be committed. For example, I could specify that any file that ends in *.php must have the property svn:eol-style set to LF.

    If you use this, you'll never have an issue with the ^M line endings again.

    As for finding them, I've been able to do this:

    $ find . -type f -exec egrep -l "^M$" {} \;
    

    Where ^M is a Control-M. With Bash or Kornshell, you can get that by pressing Control-V, then Control-M. You might have to have set -o vi for it to work.