Mac Batch processing of text files - normalize line endings

wrldwzrd89

macrumors G5
Original poster
Jun 6, 2003
12,106
73
Solon, OH
Right, so I have 200+ plain text files that all need the same fix: Change their line endings to DOS/Windows format. Is there a simple way to do this with the Terminal and/or AppleScript? They're not all in the same folder, but writing a shell script to traverse the folder structure shouldn't be too hard. What I am looking for is the commands to use to apply the fix to each text file. If this is better done with AppleScripting of TextWrangler, so be it. I'm fine with that.
 
Last edited:

balamw

Moderator
Staff member
Aug 16, 2005
19,075
963
New England
FWIW My cheap and sleazy way around this is to zip the files and use info-zip unzip's -a option to treat all files as ASCII, but that won't work to get dos endings on a unix system.

EDIT: This Wikipedia article may come in handy. http://en.wikipedia.org/wiki/Unix2dos. If the files are a mixed bag already, I'd use the zip approach mentioned above to normalize the files to unix endings before translating. Otherwise you run the risk of getting some funky line endings like \r\r\n on some occasions.

B
 
Last edited:

wrldwzrd89

macrumors G5
Original poster
Jun 6, 2003
12,106
73
Solon, OH
FWIW My cheap and sleazy way around this is to zip the files and use info-zip unzip's -a option to treat all files as ASCII, but that won't work to get dos endings on a unix system.

EDIT: This Wikipedia article may come in handy. http://en.wikipedia.org/wiki/Unix2dos. If the files are a mixed bag already, I'd use the zip approach mentioned above to normalize the files to unix endings before translating. Otherwise you run the risk of getting some funky line endings like \r\r\n on some occasions.

B
Thanks, I'll give this a try. What's info-zip? If that's the CLI zip utility, I think I'm good to go.
 

ScoobyMcDoo

macrumors 65816
Nov 26, 2007
1,185
34
Austin, TX
The other way is to use the utility, unix2dos. This does not appear to come stock on OS X, so you will have to get it via fink or macports, or perhaps just d/l the code.

Anyway, once that is installed you could use the command:

find . -name *.txt -exec unix2dos {} \;
 

wrldwzrd89

macrumors G5
Original poster
Jun 6, 2003
12,106
73
Solon, OH
Got it!

Using the following terminal commands:
Code:
cd (drag directory to be fixed here)
find . -name *.txt -exec perl -i -p -e 's/\r//' file \;
find . -name *.txt -exec perl -i -p -e 's/\n/\r\n/' {} \;
The second command fixes everything to UNIX style.
The third changes the files to Windows style, as I want.

Fortunately, I had no Mac-style text files.