Solved

Recursive shell script - most elegant implementation?

Posted on 2002-05-30
11
1,209 Views
Last Modified: 2010-05-18
I've been working on a shell script to rename files in a directory tree.  The purpose is to remove spaces from the file names of some photos so that they can be more easily put on the web (fewer %20 instances).  I'm working in the Bourne shell, and have mastered the task of renaming all the files in the current directory, using a "for Original in *" type of construct to look at each file the directory, squeeze the spaces out of it, rename it.  The current implementation looks something like this (from memory, may not be perfect):

#!/bin/sh

for Original in *
do
  Squeezed = `echo $Original | sed 's/ //g'`
  if [ "$Original" != $Squeezed ]
  then
    mv \"$Original\" $Squeezed
  fi
done


The next advancement I'd like to make is to recursively run the script - test each file with [ -d $Squeezed ] and then call the script to work on the new directory.

The trouble is how to refer to the script itself in order to run it successively from various places within the directory tree.  The solutions that come to mind are:

1. copy the script to tmp and execute it from that fixed location, then delete it when done, a la
cp $0 /tmp/$$.sqzit
<do recursive stuff>
rm /tmp/$$.sqzit

2. Put the whole working part of the script into a Here document, then copy that into each directory as we go and execute it from there (whew, the conceptual image of that is interesting).  Kind of makes it into a two part script.

Usually when I find myself proposing a solution this complicated I later discover that Unix has some obscure but elegant way to accomplish what I'm trying to do... does anyone have any simple way to run a new instance of the script that is currently running, in a new directory and with a new command line?

Suggestions and pointers to good scripting tutorials/resources on the web welcome.
0
Comment
Question by:ckurt99
  • 3
  • 3
  • 3
  • +2
11 Comments
 
LVL 14

Expert Comment

by:chris_calabrese
ID: 7045465
Any reason you want to do the tree traversal in shell rather than simply calling find?

find . -type f -print | while read pathname
0
 
LVL 3

Author Comment

by:ckurt99
ID: 7045496
Thank you for responding...

Initially, I did intend to use find; however, I ran into trouble with the pathnames interacting (read: failing) with the mv when the dealing with directories.  As I recall, I was generating commands like this that didn't work:

mv "/usr/~kurt/My Directory" /usr/~kurt/MyDirectory

After experimenting a bit it seemed like the only way to rename a directory was to be in the directory and do a simple rename:

mv "My Directory" MyDirectory

Hence the traversal in the shell... but I'm open to suggestions.
0
 
LVL 38

Expert Comment

by:yuzh
ID: 7045770
You do have to use recursive call for the job:

you can modify your script as a ksh script, and make your original script as a function of the main script, and use function call inside the script to do the job.

eg.

#==========================================
#!/bin/ksh

#define your vars here.


#put your script here as a function, use dir as arg
mvfile()
{

cd $1           #move to the dir you want to change
for Original in *
do
 Squeezed = `echo $Original | sed 's/ //g'`
 if [ "$Original" != $Squeezed ]
 then
   mv \"$Original\" $Squeezed
 fi
done

}

# main body of your script.
  #do whatever you want to create a list of dir to be cahnge

  for dir in `cat MYDIRLIST` ; do

   mvfile ${dir}

  done

.........
 exit 0

# Note you can have 2 arg for your function if your what to move file from one dir to another


0
 
LVL 5

Expert Comment

by:ecw
ID: 7046438
find . -type d | while read dir ; do
  (
  cd $dir
  for Original in *
  do
   Squeezed=`echo "$Original" | sed 's/ //g'`
   if [ "$Original" != "$Squeezed" ]
   then
     mv "$Original" "$Squeezed"
   fi
  done
  )
done


0
 
LVL 14

Accepted Solution

by:
chris_calabrese earned 100 total points
ID: 7046750
Since directories may also be renamed...

 find . -type d -depth | while read dir ; do
 (
 cd $dir
 for Original in *
 do
  Squeezed=`echo "$Original" | sed 's/ //g'`
  if [ "$Original" != "$Squeezed" ]
  then
    mv "$Original" "$Squeezed"
  fi
 done
 )
done
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 51

Expert Comment

by:ahoffmann
ID: 7050391
find . -exec echo echo {} @@ {} \;|awk -F@ '{print $1 "`mv \""$3"\"|tr -d '"'"' '"'"'`" }'|sh

# above asumes that there're no filenames containing @
0
 
LVL 51

Expert Comment

by:ahoffmann
ID: 7050398
oops, last suggestion is wrong, please use following instead:

find . -exec echo mv {} @@ {} \;|awk -F@ '{print $1 "`echo \""$3"\"|tr -d '"'"' '"'"'`" }'|sh
0
 
LVL 14

Expert Comment

by:chris_calabrese
ID: 7051140
Interesting, but you'll still want -depth on the find.
0
 
LVL 51

Expert Comment

by:ahoffmann
ID: 7051259
somebody asked for -depth ?
or even existance of "MyDirectory" when "My Directory" exists also ?-)
0
 
LVL 3

Author Comment

by:ckurt99
ID: 7051460
Whew, it's getting deep now!  Thanks to all who responded.  I've learned something from each of you... well, OK, I haven't learned ahoffman's yet, but given time I will.  I wouldn't have dreamed that this could be reduced to a one-liner, but then I'm forgetting that All Things Are Possible With Awk (ATAPWA?).

I've chosen Chris Calabrese' second comment as the answer, and will post sharing points questions for yuzh, ecw, and ahoffman.
0
 
LVL 3

Author Comment

by:ckurt99
ID: 7074721
Just for the record, I want to post a small correction to this script, caused by the fact that find reports files with relative pathnames.  This required me to go back to the starting directory before jumping to the directory to be processed.  The corrected script is shown below.  There is a further refinement left as an exercise for the reader: handle the error case where a new file name already exists.  Thanks to all who responded.

#!/bin/sh

StartDir=`pwd`

find . -type d -depth -print | while read MyDir ; do
(
  cd "$MyDir"

  for OriginalFile in *
  do

    ShortName=`echo $OriginalFile | sed 's/ //g'`

    if [ $ShortName != "$OriginalFile" ]
    then
      mv "$OriginalFile" "$ShortName"
    fi

  done

  cd "$StartDir"
)
done
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

My previous tech tip, Installing the Solaris OS From the Flash Archive On a Tape (http://www.experts-exchange.com/articles/OS/Unix/Solaris/Installing-the-Solaris-OS-From-the-Flash-Archive-on-a-Tape.html), discussed installing the Solaris Operating S…
Every server (virtual or physical) needs a console: and the console can be provided through hardware directly connected, software for remote connections, local connections, through a KVM, etc. This document explains the different types of consol…
Learn how to navigate the file tree with the shell. Use pwd to print the current working directory: Use ls to list a directory's contents: Use cd to change to a new directory: Use wildcards instead of typing out long directory names: Use ../ to move…
In a previous video, we went over how to export a DynamoDB table into Amazon S3.  In this video, we show how to load the export from S3 into a DynamoDB table.

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now