Skip to main content

Sponsors

Apply dos2unix on Text Files Recursively using BASH

I found that current dos2unix will produce an intermediate file and stop when it encounters a directory in the arguments. And it cant process folders recursively. Hence, I wrote these scripts to help me to convert all text files in a list of files and folders into DOS or UNIX format.

Explore directories and files recursively.

explore()
{
        local file=""
        ls -1 | while read -r file
        do
                # Recursively explore if we found a directory.
                if [ -d "$file" ] ; then
                        echo "Entering $file"
                        pushd "$file" > /dev/null
                        explore
                        echo "Leaving $file"
                        popd > /dev/null
                # Process it if we found a text file.
                elif [ "`${FILE} ${file} | ${GREP} text`" != "" ] ; then
                        # echo "Processing: $file"
                        $DOS2UNIX "${file}"
                fi
        done
} # end of explore()

Process each of the files and folders given in the command line.

for file in $@ ; do
        # FIXME: I should have put these into a subroutine to reduce code duplications in explore().
        # However, I'm not familiar with subroutines in BASH yet.
        if [ -d "$file" ] ; then
                echo "Entering $file"
                pushd "$file" > /dev/null
                explore
                echo "Leaving $file"
                popd
        elif [ "`${FILE} ${file} | ${GREP} text`" != "" ] ; then
                $DOS2UNIX "$file"
        fi
done

For the entire file, see xman_dos2unix in xman utility (latest) under GPL.

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.