grep -c $'\r\n' file returns the exact same number as grep -c $'\n' file, it shows the number of LF in the file instead of the number of CRLF. (The file definitely does not contain that number of CRLF.) How can I determine the exact number of CRLF occurrences?

I've tried the following commands, none of them return the right number:

grep -c $'\r\n' file
grep -c $"\r\n" file
grep -c '\r\n' file
grep -c "\r\n" file
  • Why not grep -c "\r\n" file ? – Costas Jan 18 '15 at 12:41
  • Tried various combinations of with and without the dollar sign, and using single or double quotes, none of them return the right number. – user779159 Jan 18 '15 at 12:55
  • Try grep -c "^M$" sample.txt (Note that ^M is Ctrl+v,Ctrl+m) – Costas Jan 18 '15 at 14:41

The pattern argument to grep is in fact a newline-separated list of patterns. Thus grep $'\r\n' searches either a CR or the empty pattern (which matches every line). This is the same as grep $'\n' which searches the empty pattern or the empty pattern.

To search for a CRLF sequence, search for a CR at the end of the line.

grep -c $'\r$' file
  • With the tiny exception of files where last byte is a \r. – user367890 Jan 18 '15 at 23:39
  • 2
    @user367890 If the last byte isn't a newline then the file isn't a text file, so the behavior depends on the grep implementation. With GNU grep, grep $'\r$' does find a CR at the end of the file. – Gilles 'SO- stop being evil' Jan 18 '15 at 23:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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