1

我正在尝试批量重命名操作系统上同一文件夹中的许多文件。

我有一个包含两个变量的数据集:oldnamenewname.

数据集中有更多的文件名,然后是需要重命名的实际文件,所以我想构建一些与数据集中的观察匹配的文件,重命名匹配的文件,然后将其移动到新位置。

例如,我在一个位置有三个文件:

filepath/to/my/files/file1.jpg
filepath/to/my/files/file2.jpg
filepath/to/my/files/file3.jpg

具有字符串变量的数据集:

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

这是程序所需的输出:

filepath/for/matches/pink.jpg
filepath/for/matches/red.jpg
filepath/for/matches/green.jpg

我需要使用!运算符来实现我想要的吗?


编辑:

到目前为止,我有一种移动比赛的方法,但不能重命名它们:

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
4

1 回答 1

2

不必要。copy您可以通过简单地使用命令来实现您想要的。

以下应该有效:

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"
        }
    }
}

只需替换本地宏inpathoutpath使用您想要的路径。

请注意,如果您还想在复制文件后删除该文件,则只需在copy命令后添加以下内容:

erase "`inpath'`fil'"
于 2018-07-19T21:12:00.703 回答