cat wc -l count lines line with defined line endings (e.g Mac OS X specific)

4

As any command-line user I sometimes want to count lines in text file with well known command:

cat some_text_file | wc -l

I face the problem on Mac OS X, which as far I have it studied is connected with different line endings (sometimes I have output from Mac OS X version of Excel which uses OS X specific line ending, which is not understandable for wc -l; After changin line endings to UNIX style e.g in SublimeText everything works as expected).

SO MY QUESTION:

Can I pass somehow to wc -l the line ending kind as somee parameter which should be used? If yes please provide some example.

andilabs

Posted 2014-03-22T02:41:56.920

Reputation: 372

Answers

7

Try

cat some_text_file | tr "\r" "\n" | wc -l

Jamil Najafov

Posted 2014-03-22T02:41:56.920

Reputation: 86

-2

Try:

strings some_text_file | wc -l

Nevin Williams

Posted 2014-03-22T02:41:56.920

Reputation: 3 725

What? This has nothing to do with what the question asked for. – G-Man Says 'Reinstate Monica' – 2014-10-22T21:17:07.840

STRINGS(1) STRINGS(1)

NAME strings - find the printable strings in a object, or other binary, file – Nevin Williams – 2014-10-25T17:59:49.240

(1) My comment may have been unnecessarily harsh; I apologize for that. However, (2) the question is about text files. As the quote from the man page you posted implies, there’s little point in running strings on text files – it’s meant for finding text in binary files. (3) echo -e "To\nbe\nor\nnot\nto\nbe;\nthat\nis\nthe\nquestion." clearly produces 10 lines, but if you pipe it into strings | wc -l, it says 2. Conversely, echo "The quïck bröwn fox jûmps över thé lazy dog." produces one line, but strings | wc -l says 6. So your suggestion yields incorrect results. … (Cont’d) – G-Man Says 'Reinstate Monica' – 2014-10-27T20:46:07.590

(Cont’d) … (4) The best that your answer could be is a more resource-expensive, complicated variant on cat some_text_file | wc -l, which, in turn, is a more resource-expensive, complicated variation on wc -l < some_text_file. None of these approaches addresses the part of the question that makes it somewhat distinctive – the fact that it’s asking about files that might end with Unix-style line endings and might end with CR+LF. What part of your answer do you think tells wc -l the kind of line ending that should be used? – G-Man Says 'Reinstate Monica' – 2014-10-27T20:47:44.687

Had I a file of the sort in question (it's unclear exactly what file format it is), I'd have tried my suggestion myself, before suggesting it. It's a quick and dirty method that occasionally works for me; it may have worked for him, or others with similar, non-specific mixed file parsing issues who happen upon this thread. – Nevin Williams – 2014-10-28T19:30:57.003