Newline / convert newline shell script

Posted by on Sep 26, 2010 in code, how to, Mac | No Comments

When pasting data to a text file, for use with python and other data editing tools, it may be better to use a code text editor, like BB Edit or Text Wrangler. These apps can save your .txt files with UNIX line returns which is necessary to make some scripts work properly.

Technically the line breaks are invisible, but using the ‘tr’ command, in a UNIX shell, you could display them as any character you like, eg:

In the terminal type:

cat /path/some/file.txt | tr '\n' 'U'

In the above example, if the input file uses UNIX style line returns, \n ,each line will have a ‘U’ at the end, or nothing if the file is using another type of return.

To change line returns from Mac to Unix in a data file, try the shell script below.

#!/bin/sh

theFile="$1"

newFile=`basename -s ".txt" $theFile`.UnixLineReturns.txt

theDir=`dirname $theFile`

echo "theFile: $theFile"
echo "newFile: $newFile"
echo "theDir: $theDir"

cat "$theFile"  | tr '\r' '\n' > "$theDir/$newFile"

Email this to someoneTweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on StumbleUponShare on RedditDigg this

Leave a Reply