[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: yet another bash question



On Tuesday 07 November 2006 16:16, Richard Lyons wrote:
> For things like saving photos to hard disk, I tend to use a few bash
> scripts to rename the files, keeping the numerical part and coding
> something else in place of the "cimg".  For example, I might change all the
> files cimg1234.jpg to cimg1299.jpg to be called foobar234.jpg to
> foobar299.jpg. I tend to modify these scripts when need arises, but the
> latest one shows an oddity I cannot understand.
>
> The script (called prep) is inline below. It removes $1 from the beginning
> of any filename in pwd and replaces it with $2, subject to a couple of
> sanity checks.
>
> Here is the output from a test run:
> --------
> richard@scatola:~/test$ ls
> ohdear  ohwonderful  oops  oopsdeardear  tutdear
> richard@scatola:~/test$ prep oops wer
>
> ... working
>     oops  ->  wer
>     oopsdeardear  ->  werdeardear
>             2 renamed --all done.
>
> richard@scatola:~/test$ ls
> ohdear  ohwonderful  tutdear  wer?  werdeardear
> --------
> My question is:  where did the question mark come from? It always occurs if
> the whole filename is substituted.
>
> Of course, someone will tell me there is a standard unix command to do
> this...
>
> richard
>
> --------here is the script:
> #!/bin/bash
> #
> prep
> # in present working directory, remove occurrences of a string at the start
> of # any filenames, and replace it by another string, subject to avoiding #
> duplicate or empty filenames
>
> # USAGE: prep [stringtoreplace [newstring] ]
>
> # have we an old string?
> if [ -n "$1" ] ; then
>   old="$1" ;
>   # if not, we ask for it
> else
>   echo "enter initial string to be replaced " ;
>   read -p "(if you leave this blank, new string will be prepended): " old ;
> fi
> lenold=${#old}
> #have we got a string to substitute?
> if [ -n "$2" ] ; then
>   pre="$2" ;
>   # if not, get string
> else
>   if [ -z "$old" ] ; then
>     prmpt="prepend" ;
>     echo "you will prepend all filenames in pwd," ;
>   else
>     prmpt="substitute" ;
>     echo "you will replace the initial string '$old' of filenames in pwd,"
> ; fi
>   read -p " -- enter new string to $prmpt: " pre ;
> fi
>
> # and do the job
> echo ;
> echo "... working"
> for f in $old* ; do
>   nowf=`basename "$f"`;
>   subf="$pre${nowf:lenold}";
>   if [ -n "$subf" ] ; then
>     if [ -e "$subf" ] ; then
>       echo "    $f not renamed because $subf already exixts"
>     else
>       echo "    $f  ->  $subf"
>       mv "$f" "$subf"
>       nr=$((co ++))
>     fi
>   else
>     echo "    $f not renamed to blank name"
>   fi
> done
> echo "            $co renamed --all done."
> echo ;
> --------end of script

I know this doesn't really directly address your question, but rox-filer has a 
nice rename feature that I use to rename photos.  I wish Konqueror had this 
feature too.

Chris

-- 
C. Hurschler



Reply to: