Bash Script for converting DOS to UNIX textfiles

By Christopher, March 7, 2010

This is a short bash script, which I have written as a homework in my studies. It converts all files in parameters from DOS to UNIX or from UNIX to DOS, depending on their current style.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/bin/bash

#fromdos - todos
# This scripts check file(s) in parameter(s) for line ends in unix or dos style and converts to the opposit one
# if file(s) does not exist a error is thrown

#Author:Christopher-Eyk Hrabia
#Date:  31.10.2009

TEMPFILE="/tmp/fromDOS_toDOS.txt"

if [[ $# -eq 0 ]];then
echo "Using:"
echo "fromDosToDos [file] ..."
echo "Explanation:"
echo "Every file in arguments will be converted to his opposit,"
echo "it means: it converts DOS style to UNIX style and otherwise"
echo "Author: Christopher-Eyk Hrabia - c.hrabia@gmail.com"
fi

args=$@
for i in $args;do
if test -a $i;then
echo "File converted: $i"

#check if DOS or UNIX
countMS=`cat $i | sed -n '/\x0D$/p' | wc -l`

if [[ $countMS -gt 0 ]];then
#DOS to Unix
echo "to UNIX"
sed 's/\x0D$//' $i > $TEMPFILE
else
#Unix to DOS
echo "to DOS"
sed 's/$/\x0D/' $i > $TEMPFILE
fi
mv $TEMPFILE $i
echo '+++++++++++++++++++++++++++++++++++++++++++'
else
echo "File does not exist: $i">&2
fi
done

have fun with it!