• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1182
  • Last Modified:

Script to move file & increment filename

I need a script that will move a file called "file.txt" from one directory to another and increment the filename during the move. So, as the "file.txt" files are moved from the source directory to the destination directory, they are renamed "file1.txt", "file2.txt", "file3.txt", etc.
0
2retread
Asked:
2retread
  • 2
  • 2
1 Solution
 
fim32Commented:
you're sure you wanna do this with perl?  perl's a little heavy for something like this.

how many files do you wanna keep?  

the easiest way to do this would be in a simple shell script (or bat for windows):

#!/bin/sh
DEST=/path/to/destination/

mv $DEST/file4.txt $DEST/file5.txt
mv $DEST/file3.txt $DEST/file4.txt
mv $DEST/file2.txt $DEST/file3.txt
mv $DEST/file1.txt $DEST/file2.txt
mv file.txt $DEST/file1.txt

and voila
0
 
ozoCommented:
my $n = 0;
for( <destination/file*.txt> ){
     $n = $_+1 if /(\d+)\w+$/ && $1 >= $n;
}
rename "source/file.txt", "destinaton/file$n.txt";
0
 
2retreadAuthor Commented:
Changed the paths and file name to match my environment. Upon executing the script for the first time, “file.txt” is moved to the archive directory and is renamed “file0.txt.” Subsequent executions of the script results in the file being overwritten with the new file, same file name, i.e., “file0.txt.” I would like the script to rename the subsequent files “file1.txt”, “file2.txt”, etc. Thanks for your help!



my $n = 0;
for( <d:/archive/file*.txt> ){
     $n = $_+1 if /(\d+)\w+$/ && $1 >= $n;
}
rename "d:/datafiles/file.txt", "d:/archive/file$n.txt";
0
 
ozoCommented:
#sorry, that should have been
    $n = $1+1 if /(\d+)\.txt/ && $1 >= $n;
0
 
2retreadAuthor Commented:
Thanks for your help!!!
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now