I am trying to batch rename many files within the same folder on my operating system.
I have a dataset with two variables: oldname
and newname
.
There are more file names in the dataset then actual files that need to be renamed so I would like to build something that matches the file with the observation in the dataset, renames the matched file, and then moves it to the new location.
For example, I have a three files in a location:
filepath/to/my/files/file1.jpg
filepath/to/my/files/file2.jpg
filepath/to/my/files/file3.jpg
A dataset with string variables:
Dataset
newname oldname
a pink files/file1.jpg
b blue files/file4.jpg
c purple files/file6.jpg
d green files/file3.jpg
e red files/file2.jpg
Here is the desired output of the program:
filepath/for/matches/pink.jpg
filepath/for/matches/red.jpg
filepath/for/matches/green.jpg
Do I need to use the !
operator to achieve what i want?
EDIT:
So far, I've got a method of moving the matches but not for renaming them:
global dir "/filepath"
global old "$dir/to/my/"
global new "$dir/for/matches"
ssc install mvfiles
preserve
keep if oldname!=.
foreach i in oldname{
mvfiles, infolder($old) outfolder($new) match(substr(`i',6,9))
}
restore
Not necessarily. You can achieve what you want by simply using the copy
command.
The following should work:
clear
input str1 letter str10 newname str15 oldname
"a" "pink" "files/file1"
"b" "blue" "files/file4"
"c" "purple" "files/file6"
"d" "green" "files/file3"
"e" "red" "files/file2"
end
local inpath "filepath/to/my/files/"
local outpath "different/filepath/for/matches/"
local files : dir "`inpath'" files "*.jpg"
local obs = _N
foreach fil of local files {
forvalues i = 1 / `obs' {
local oldname = oldname[`i']
if substr("`fil'", 1, strpos("`fil'", ".") - 1) == substr("`oldname'", 7, .) {
local newname = newname[`i']
copy "`inpath'`fil'" " `outpath'`newname'.jpg"
}
}
}
Just replace the local macros inpath
and outpath
with your desired paths.
Note that If you also want to delete the file after you copy it, then just add the following after the copy
command:
erase "`inpath'`fil'"