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.