If a file has DOS/Windows-style CR-LF line endings, then if you look at it using a Unix-based tool you'll see CR ('\r') characters at the end of each line.
This command:
grep -l '^M$' filename
will print filename
if the file contains one or more lines with Windows-style line endings, and will print nothing if it doesn't. Except that the ^M
has to be a literal carriage return character, typically entered in the terminal by typing Ctrl+V followed by Enter
(or Ctrl+V and then Ctrl+M). The bash shell lets you write a literal carriage return as $'\r'
(documented here), so you can write:
grep -l $'\r$' filename
Other shells may provide a similar feature.
You can use another tool instead:
awk '/\r$/ { exit(1) }' filename
This will exit with a status of 1
(setting $?
to 1
) if the file contains any Windows-style line endings, and with a status of 0
if it doesn't, making it useful in a shell if
statement (note the lack of [
brackets ]
):
if awk '/\r$/ { exit(1) }' filename ; then
echo filename has Unix-style line endings
else
echo filename has at least one Windows-style line ending
fi
A file can contain a mixture of Unix-style and Windows-style line endings. I'm assuming here that you want to detect files that have any Windows-style line endings.
-A
to cat. One tip though would be to usecat -A file | less
if the file is too big. I'm sure it's not uncommon to have to check file endings for a particularly long file. (Pressq
to leave less) – Nicholas Pipitone Aug 02 '19 at 20:15cat -ve
can be used as well and is more portable. – Oskar Skog Jan 28 '20 at 18:52cat
(bat
), then it's even more clear visually. – psygo Feb 21 '21 at 19:19cat -A
did not work on macOS butcat -ve
was fine. – user118967 Mar 11 '21 at 07:39cat
/less
replacement to have anyway) thenbat -A myfile
actually make this very nice to read, by displaying formatted␍
and␊
as applicable – Trevor Gross Aug 30 '22 at 07:35