As simple and straightforward as they may seem, text files still harbor an opportunity for compatibility problems. Different operating systems have traditionally used different ways to indicate line endings (line breaks). Mac OS has traditionally used the Carriage Return character (ASCII chcracter 13, aka CR or ^M) to indicate line breaks; unix has traditionally used the Line Feed character (ASCII 10, aka LF or ^J). Since Mac OS X derives from both heritages, it winds up using a mix of the two in various contexts. But most command line utilites only understand (and produce) files with unix-style breaks.Just to make things even more fun, there’s actually a third variant: MS-DOS its successors use a carriage return followed by a line feed to indicate a line break. Few Macintosh programs will generate such files, but if you need to deal with a file that came from a PC, you’ll probably want to convert it to a more native format on the Mac.
Fortunately, it’s fairly easy to convert the formats back and forth on the command line. Here are some examples of how to transform files back and forth:
tr '\r' '\n' <macfile.txt >unixfile.txt convert the Mac-format file macfile.txt to unix format, and save the result as unixfile.txt. tr is a program that does character substitution, and in this case it's simply being used to replace CR (written \r on the command line) with LF (written \n) throughout the file. tr '\r' '\n' <macfile.txt | grep fnord convert the Mac-format file macfile.txt to unix format, then use grep to search the file for the word "fnord". (Note: grep doesn't understand Mac-style line breaks.) tr '\n' '\r' <unixfile.txt >macfile.txt convert the unix-format file unixfile.txt to Mac format, and save the result as macfile.txt. perl -p -e 's/\r/\n/g' macfile.txt >unixfile.txt convert the Mac-format file macfile.txt to unix format, and save the result as unixfile.txt. This is functionally identical to the first example, but since perl is actually a very general programming language, it can also do some other useful things... BTW, he -e means the program will be the next thing on the command line ('s/\r/\n/g' - perlese for replace all \r's with \n's), and the -p means do this for each line of the file. perl -pi -e 's/\r/\n/g' textfile.txt convert the file textfile.txt from Mac-style (CR) line breaks to unix-style (LF), and replace the original file with the converted version (that's what the -i means). perl -pi -e 's/\r\n?/\n/g' textfile.txt convert the file textfile.txt from Mac-style (CR) or PC-style (CRLF) line breaks to unix-style (LF), and replace the original file. perl -pi -e 's/\r\n?/\n/g' *.txt convert all text files (or rather, files with .txt extensions) in the current directory to unix-style breaks. Note that any that were already in unix format will not be changed. perl -pi -e 's/\n/\r/g' textfile.txt convert the file textfile.txt from unix-style (LF) line breaks to Mac-style (CR), and replace the original file. Source Source