Suppose I'm given a variety of files, some with line endings of \r, \n and \r\n. How would I efficiently count the number of lines in a file when I don't know what to expect beforehand?Obviously wc -l won't work if there are Mac line endings.Grep appears to be very inaccurate when used:grep -o '\r' /path/to/file.txt | wc -lGives 1041 lines but there are actually only 299 lines, and nano is able to confirm that by auto-converting from Mac format.It also doesn't provide the versatility I was hoping for because grep -o '[\r\n]+' /path/to/file.txt | wc -l returns a count of 0.How do I do this correctly?
Counting number of lines in file regardless of line ending char
grep;wc
Your grep command was giving far too many matches because grep uses Basic Regular Expressions, which don't give special meaning to \r -- it was counting occurrences of the letter r.tr does recognise \n and \r, so it can find all the matches, and let wc -c count them byte-by-byte:tr -d -c '\n\r' < file.txt | wc -cBut as your file may also contain Windows/DOS line-endings (\r\n), those would get counted twice.  You will need an additional step to convert any DOS-style line-endings to one of the other forms, then count individual line-end characters as before:sed 's/\r$//' file.txt | tr -d -c '\n\r' | wc -cUnfortunately, sed doesn't always recognize \r, either.  You may need to use some other way to specify a carriage-return, such as the shell's own escaping, the echo command, or putting the sed script in a file.