Home:ALL Converter>how to distinguish a file with DOS newlines from a shell script

how to distinguish a file with DOS newlines from a shell script

Ask Time:2016-07-27T07:53:28         Author:Imani Mason

Json Formatter

I'm trying to write a shell script which can determine whether the lines in an input file end with DOS (CR/LF) or Unix (LF) newlines.

How can I make this determination?

Author:Imani Mason,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/38601644/how-to-distinguish-a-file-with-dos-newlines-from-a-shell-script
tripleee :

If examining the first line is sufficient, something like\n\nperl -ne 'exit ($_ =~ /\\r$/)' file\n\n\nYou could do the same in Bash;\n\nlffile () {\n local REPLY\n read -r <\"$1\"\n case $REPLY in *$'\\r') return 1;; *) return 0;; esac\n}\n\n\nThis requires the $'\\r' C-style strings of Bash >= 3.x. If you can reliably and portably embed a literal carriage return character in your script, you could even use sh for this, with that minor change. The following uses a pesky global to hold the carriage return character:\n\nlffile_cr=$(printf '\\r')\nlffile () {\n # local is not POSIX; simply overwrite REPLY\n read -r <\"$1\"\n case $REPLY in *\"$lffile_cr\") return 1;; *) return 0;; esac\n}\n\n\nIn the most general case, a file could have mixed line endings, but if we assume that line endings are consistent (and/or that getting a 50% hit or miss rate for that obscure corner case is acceptable), reading the first line is sufficient.",
2016-07-27T07:56:16
Charles Duffy :

One approach that avoids relying on external tools such as file follows:\n\n#!/bin/bash\n# ^^^^- important! not /bin/sh, and do not run with \"sh scriptname\"\n\n# if given a command-line argument, redirect from it as stdin\nif [ -n \"$1\" ]; then\n exec <\"$1\" || exit\nfi\n\n# Read a single line from stdin into a variable\nif ! IFS= read -r line; then\n # we were unable to read a line\n echo \"Invalid or Empty\"\n exit 1\nfi\n\n# Check whether the last character of that line is a CR\ncase $line in\n *$'\\r') echo \"DOS\" ;;\n *) echo \"UNIX\" ;;\nesac\n\n\nThis works because in bash (though not POSIX sh), $'\\r' is syntax for a carriage return (CR) character. Since read reads up to the first LF seen, in a DOS file, the last character in a line read from that file will be a CR.",
2016-07-27T00:12:36
yy