pacmaninbw
pacmaninbw

Reputation: 535

Bash script to convert all files of a given type from Unix to Dos Format

I need to be able to go back and forth between CentOS and Windows for C++ projects that I am developing on both systems. I want to be able to convert all files of a given type such as *.cpp, *.h or *.txt from Unix to Dos.

I have a bash script that converts a single file, but I'd like to be able to type in either just the extension of the file type or *.FILETYPE to convert all the files in a given directory of that type.

Here is the working script, what do I need to do to make it work for more than one file at a time. I've tried using a for loop but I get syntax errors.

#! /bin/sh

# Convert a text based file from Unix Format to Dos Format
# The Output file should be the name of the input file with
# WF inserted before the file extention
#
# Examples
#    convert Unix format abc.txt to abcWF.txt Windows Format 
#    convert Unix format abc.cpp to abcWF.cpp Windows Format 

echo "In u2w FileToConvert = $1"
    FileBase=$(basename $1)
    FileExtension="${FileBase##*.}"
    FileBase="${FileBase%.*}"
    OutputSuffix="WF.$FileExtension"
    OutputFile="$FileBase$OutputSuffix"
    commandment="unix2dos -n $1 $OutputFile"
    echo $commandment
    unix2dos -n $1 $OutputFile
    echo "diff -w $1 $OutputFile"
    diff -w "$1" "$OutputFile"

exit

Example run

$  bd2w TestResults.txt
In u2w FileToConvert = TestResults.txt
unix2dos -n TestResults.txt TestResultsWF.txt
unix2dos: converting file TestResults.txt to file TestResultsWF.txt in DOS format ...
diff -w TestResults.txt TestResultsWF.txt

Upvotes: 0

Views: 1668

Answers (1)

John Kugelman
John Kugelman

Reputation: 361645

Wrap the script in a for file in "$@" loop and replace all mentions of $1 with $file.

#!/bin/sh

for file in "$@"; do
    echo "In u2w FileToConvert = $file"

    FileBase=$(basename "$file")
    FileExtension="${FileBase##*.}"
    FileBase="${FileBase%.*}"
    OutputSuffix="WF.$FileExtension"
    OutputFile="$FileBase$OutputSuffix"

    echo "unix2dos -n $file $OutputFile"
    unix2dos -n "$file" "$OutputFile"

    echo "diff -w $file $OutputFile"
    diff -w "$file" "$OutputFile"
done

Upvotes: 2

Related Questions