-   Linux - General (
-   -   How to recursively rename files using their directory name pattern (

ceg4048 09-28-2005 09:57 AM

How to recursively rename files using their directory name pattern
I have a project in which I need to convert some .tif files and assemble them into a .pdf book. The conversion is not a problem as I can use Adobe in windows however, there are a large number of files (50,000) distributed over several hundred directories . The pattern of the directory names and files is similar to the following examples:


My goal is to search through all the target directories and extract all to a single directory, however since they are all similarly named (page01.tif, page02.tif etc.) I need to rename them and keep track of where they came from such that each file combines it's orignal directory name with it's original filename appended, similary to the following pattern:


I'm having difficulty coming up with a robust string of commands that can do this renaming non-interactively. Could anyone offer a command string to accomplish this?


homey 09-28-2005 12:37 PM

This might get you started. Make the script executable and run it like this example....
./test "/mnt/tech/achome/Music/mp3 files"

mkdir /home/images



        echo "Usage: $0 [directory]"
        exit 1;

test -d "$1" || usage

name=`echo "$dir" | cut -d/ -f2- | tr '/' '_'`
ls "$dir" | grep -e "[:alnum:]" | \
while read i; do
  j=`echo "$i" | sed 's/\(.*\)/'"$name"'_\1/'`
  cp -v "$dir/$i" "/home/images/$j"

Edit: Maybe you better not re-create /home/images after you have already put files into it.

ioerror 09-28-2005 01:16 PM

A simple script incorporting the following should suffice:

There are any number of ways to suck up the filenames, e.g.

filelist=(find ~/whatever)

With zsh, you can do recursive globbing, usnig a **.


but don't try that in bash!

Once you have your list of filenames, they just need
a little massaging,

Take a filename:


With zsh, you can nest parameter expansions, but bash can't,
as far as I know, so I'll seperate them:

First, strip off the leading path name, using ${...#...}


(don't forget the trailing slash). This will leave you with "a/b/c/d.e"

Now replace each / with an _, using a ${...//...} expansion (rtfm ;)


foo is now, of course, "a_b_c_d.e". Voila!

Now just mv/cp/ln the original filename to $foo.

All times are GMT -5. The time now is 09:07 PM.