recursively changing chars in filenames

Tim Frost timfrost at xtra.co.nz
Sun Jun 28 09:03:02 UTC 2009


On Sat, 2009-06-27 at 10:54 -0700, Smoot Carl-Mitchell wrote:
> On Sat, 2009-06-27 at 18:54 +0200, Soren Orel wrote:
> > Hi
> > I wrote a little script that removes spaces, dashes, and so on from
> > the filenames in a directory ($1), and lowercase all filename letters,
> > etc.
> > 
> > how could I complete the script, that so it will "recursively" do the
> > same thing?
> 
> You could stick it in "find" and have find do the recursion.
> 
> find . -type d -exec your_script {} \;

This will break for directories that are renamed, because the script
will rename directories before they have been examined.  By adding the
'-depth' option, you tell the find command to use 'depth-first' - i.e.
to process the contents of a directory before it processes the
directory.

So Soren can run
  find . -depth -type d -exec your_script "{}" \;
after remembering to quote the parameter $1 in the script.


Making the existing script recursive is more complex, because it has to
handle the recursion itself.  However, it does appear that the loop code
  find . -depth -type d -print | while read d
  do
   pushd "$d"
    ...
   popd
  done

will work even for directories that have embedded spaces (where the line
'...' represents Soren's original code).  Note that I use pushd/popd
because:
* the original code assumes that it is in the directory to be processed
* directory names are relative to the directory where the find started
The pushd needs quotes because otherwise a directory name with spaces
will still be split by the shell.

The code 'find . -type d -print | while read d ' works (unless the file
name DOES include a newline), because find prints a newline ("\n" or
0x0a) between file names, and the shell built-in read function uses
newline as its default delimeter.


Tim

-- 
Tim Frost <timfrost at xtra.co.nz>





More information about the ubuntu-users mailing list