Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

special renaming of multiples files

Status
Not open for further replies.

vispr

MIS
Oct 19, 2001
2
PR
Hi All,

I am trying to create a script where I can rename one file located on a directory with the directory name.

for example :-

Change abc123file.txt on directory mydir01 to mydir01.txt

The previous listing is mydir01\abc123file.txt and after the rename the listing should be mydir01\mydir01.txt and so on.


I have to do this over 167 directories. All those directories are located on a master directory.

Any suggestions would be welcomed.

Thanks,
Hector.
 
Hector,

Is there *ALWAYS* just the one file in the directory? Mike
michael.j.lacey@ntlworld.com
Email welcome if you're in a hurry or something -- but post in tek-tips as well please, and I will post my reply here as well.
 
There's more than one file on each directories but only one is going to be renamed with the directory name. The others files remains the same. The file to be renamed has the same name over all directories.
 
Inn an email vispr told me that the file to be renamed always has the same name.

So - renaming these files is a three step operation.

1 - in a loop, get the directory names
2 - getting the name of the directory containing it
3 - using that name to rename the file

ok
[tt]
#!/bin/bash

base=$1 || base='.'
cd $base || exit 1
oldfile='afile'
newfile='bfile'

echo "# $0: base directory is $base"
echo "# $0: old filename is $oldfile"
echo "# $0: new filename is $newfile"

for dir in $(ls)
do
if [ -d $dir ]
then
dir=$(basename $dir)
echo "mv $dir/$oldfile $dir/$newfile"
fi
done
[/tt]

Now - the observant amongst you will notice that I'm a coward. :) This script doesn't actually do anything, it just prints out the commands.

Before you rename any files you have to satisfy yourself that it's "doing the right thing". Like this:

put the above script into a file named, say, special_mv and then make that file executable with the command:

chmod +x special_mv

then run special_mv and redirect its output into another file, say, special_mv.output

have a good look at the commands in special_mv.output

once you are comfortable that special_mv.output will do exactly what you want, run the commands in the file with the command:

. ./special_mv.output

Please be careful, mv deletes files. It creates a new name for the file and then deletes the old name - and there's no 'undelete' or 'unmv' command in UNIX. Mike
michael.j.lacey@ntlworld.com
Email welcome if you're in a hurry or something -- but post in tek-tips as well please, and I will post my reply here as well.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top