Click to See Complete Forum and Search --> : [SOLVED] Script help on Copying and Renaming files


Vectorman
01-26-2005, 07:52 PM
I need some scripting help.

I have a directory of jpg's. I want a script to go through this directory and all of it's subdirectories and find all the files labeled *_i1_*.jpg (useing * as wildcards) When it finds a file I need it to copy the file to a different directory and label it as the directory it came out of.

so if I have a file named v0001_i1_650.jpg in a directory named screenshots I want it copied to the directory named thumbnails and lable the file screenshots.jpg

Is this possible?

if so What would the script look like?

Thank you
Joel

bwkaz
01-26-2005, 08:14 PM
Well... something like this might work. Create a script named "movefile", and make it executable. Make it look like this:

#!/bin/bash

# Get the directory the file is in
olddir="$(dirname "$1")"
# Get the last path component of that directory
newfname="$(basename "$olddir").jpg"

# Get the new filename
newpath="$PWD/thumbnails/$newfname"

echo "Old dir: $olddir"
echo "New filename: $newfname"
echo "New full path: $newpath"

# mv "$1" "$newpath" Then:

/path/to/movefile /path/to/one/of/the/files/blah.jpg

as a test. If the various directories and files are OK, then remove the comment from the "mv" command, comment out the three "echo" commands, and do this:

find /path/to/search -type f -name '*_i1_*.jpg' -exec /path/to/movefile {} \;

to actually move them all.

Vectorman
01-26-2005, 11:29 PM
That worked sorta. what I found out is that I need a different directories name.

Here is a sample path listing

/pictures
/person
/thumbnails
/*_i1_*.jpg


I need the file named after the person directory.

Thank you for any and all help.

Joel

bwkaz
01-27-2005, 09:04 PM
Ah. You could introduce another dirname before the basename:

# Get the directory the file is in
olddir="$(dirname "$1")"
# Get the directory above that
olddir2="$(dirname "$olddir")"
# Get the filename to create
newfname="$(basename "$olddir2").jpg"

tomcorrick
01-28-2005, 05:25 AM
Use the find command as follows :

find /start_dir -name '*jpg' -exec cp {} /new_dir \;

Where /start_dir is the directory that you are starting from and '*jpg' (or similar) is the pattern you are looking for.

bwkaz
01-28-2005, 07:44 PM
Yes... but, err, that won't change the filenames. ;)

That command was basically my first reaction too -- but when I saw that Vectorman wanted to name the files the same as the directory that they came out of, I realized it'd be really hard to get find to do it. Hence the script. (find's -exec doesn't use a shell to do the execution, so if you need to do shell-like things in the command (like grabbing the output of dirname / basename, for example), it's much easier to just write a script.)

Vectorman
01-29-2005, 03:02 PM
placing the second dir statement in the script worked like a charm.

Thank you so much, you saved me from hours of tedious work.
Joel