Monday, December 29, 2014

Bash Script to Cleanup File

This bash script will do three things: 1. Remove Carriage Return (\r) 2. Replace tab character with four spaces (configure as you want) 3. Add a trailing line feed to the file

#!/bin/bash

platform='unknown'
unamestr=`uname`
if [[ "$unamestr" == 'Darwin' ]]; then
   platform='MAC'
elif [[ "$unamestr" == *CYGWIN* ]]; then
   platform='WIN'
elif [[ "$unamestr" == "Linux" ]]; then
   platform='LINUX'
fi

file=$1

# Remove \r
tr -d '\r' < $file > $file.new
rm $file
mv $file.new $file

# replace \t with space
tr '\t' '    ' < $file > $file.new
rm $file
mv $file.new $file

if [[ $platform == 'MAC' ]]; then
  # On Mac, add trailing \n
  sed -i '' -e '$a\' $file
else
  sed -i -e '$a\' file
fi

No comments:

Post a Comment