Re: spaces to dashes with exception

From: Chris F.A. Johnson (cfajohnson_at_gmail.com)
Date: 07/08/05


Date: Thu, 7 Jul 2005 19:48:32 -0400

On 2005-07-07, Sebastian Luque wrote:
> "Chris F.A. Johnson" <cfajohnson@gmail.com> wrote:
>
> [...]
>
>>> Looking at _onedash_nospace and the second call, I suppose it can't.
>>
>> Why would you suppose that?
>
> Sorry I meant to ask whether $file could stand for a directory that
> _onedash_nospace could act on recursively, not just the directory *name*.

   _onedash_nospace does not act on a file or a directory; it acts on
   a single string.

> However, if I have a sample directory with:
>
>> sluque[shell]$ ls -al
><other files snipped for clarity>
> drwxr-xr-x 4 sluque users 4096 2005-07-07 09:45 .
> drwxr-xr-x 5 sluque users 4096 2005-07-04 00:07 ..
> -rw-r--r-- 1 sluque users 0 2005-07-07 09:44 atest-- abc
> drwxr-xr-x 2 sluque users 4096 2005-07-07 09:44 testing ab- c
>
> and, once _onedash_nospace has been defined, I do:
>
>> sluque[shell]$ _onedash_nospace *
>> sluque[shell]$ echo $_ONEDASH_NOSPACE
> atest-asd
>
>
> It didn't pick up the directory.

    Of course not; its function is to massage its first argument,
    nothing more.

> Supplying 'testing\ as-\ d/' as
> argument is fine though. Obviously, I'm missing something here.

    You have to supply each filename, one at a time, to the function,
    then do whatever you want to do with its result.

    When writing a program, always break it down into its parts and
    code each one, making sure it works before going on to the next
    one.

    For your task, the next step is to incorporate the function into
    code that does the actual changing of the name of the file, e.g.:

fix_file()
{
   file=$1
   _onedash_nospace "$file"
   if [ "$_ONEDASH_NOSPACE" != "$file" ]
   then
      mv "$_ONEDASH_NOSPACE" "$file"
   fi
}

    Then to fix all the files in a directory:

fix_dir()
(
   cd "$1"
   for f in *
   do
     fix_file
   done
)

    If you want to do it recursively, either use find or test each
    file to see whether it is a directory, then call fix_dir with it
    as an argument.

    There are many ways to do it; which you use depends on exactly
    what you want to do.

-- 
    Chris F.A. Johnson                     <http://cfaj.freeshell.org>
    ==================================================================
    Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
    <http://www.torfree.net/~chris/books/cfaj/ssr.html>