dos2unix

How to run dos2unix on all files with all extensions in a directory and its sun-directories?


Say I am in a folder named Folder. This folder have several files with different file types, and several subfolders called, SubFolder1, SubFolder2, etc. Each of these subfolders have files and subfolders inside them. I want to run dos2unix on ALL files in Folder, no matter they are in the main folder or in one of several sub-directores. Absolutely everything. How can I do that? To my knowledge, running

dos2unix *

works only on the files located in the main folder.


Solution

  • First solution (general)

    The standard find program is designed precisely for that kind of tasks. Something along the lines of:

    find Folder/ -type f -exec dos2unix '{}' '+'
    

    This command

    1. explores Folder/ recursively,
    2. selects all files which are of type f (regular files, by contrast with directories, symbolic links and other types of special files),
    3. and executes dos2unix with all selected filenames.

    '{}' is a placeholder which indicates where in the command you want the filename(s) to be inserted, and '+' terminates the said command. You can also run dos2unix once for each filename (by changing '+' with ';'), but since dos2unix accepts an arbitrary number of input arguments, it’s better to use it (as it avoids spawning many processes).

    find has many more options, you can find them in the manual page (link above).

    Second solution (specific to your problem)

    If your shell is Bash, Bash supports recursive wildcards (other shells such as zsh probably have a similar feature). It is disabled by default, so you have to change a shell option:

    shopt -s globstar
    

    Then, ** is a wildcard that selects everything recursively (including directories and other special files, so you may need to filter it). After that, you can try:

    dos2unix Folder/**
    

    If you want the wildcard to actually select absolutely everything, including filenames starting with a dot (hidden files), you’ll also need to set another option: shopt -s dotglob.