Newline / convert newline shell script

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:
[shell]
cat /path/some/file.txt | tr ‘\n’ ‘U’
[/shell]

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.

[shell]
#!/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"
[/shell]

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>