Stata 如何批量修改文件名

今天有个小伙伴遇到了这样的问题,他想把文件夹里面,例如 “北京市-天津市.dta” 文件重命名为 “天津市-北京市.dta”。

这里我们先创建一个示例文件夹“test”,里面有两个文件:

  • a-b.txt
  • c-d.txt

首先我们把所有的文件名读取到 Stata 中:

cd "~/Desktop/Stata 如何批量修改文件名"

*- 文件名读取为 dta 数据
local files: dir "test" files "*.txt"
di `"`files'"'

*> "a-b.txt" "c-d.txt"

local n: word count `files'
di "`n'"

clear
set obs `n'
gen oldfile = ""
forval i = 1/`n' {
local tmp: word `i' of `files'
replace oldfile = "`tmp'" in `i'
}

list

*> +---------+
*> | oldfile |
*> |---------|
*> 1. | a-b.txt |
*> 2. | c-d.txt |
*> +---------+

然后我们提取文件名的三个部分:

gen a = ustrregexs(1) if ustrregexm(oldfile, "(.*)-(.*)\.(.*)")
gen b = ustrregexs(2) if ustrregexm(oldfile, "(.*)-(.*)\.(.*)")
gen c = ustrregexs(3) if ustrregexm(oldfile, "(.*)-(.*)\.(.*)")

list

*> +-----------------------+
*> | oldfile a b c |
*> |-----------------------|
*> 1. | a-b.txt a b txt |
*> 2. | c-d.txt c d txt |
*> +-----------------------+

根据这三个变量创建新的文件名:

gen newfile = b + "-" + a + "." + c

最后再循环把旧文件的内容 copy 到新文件中即可:

cap mkdir "test2"
forval i = 1/`n' {
copy "test/`=oldfile[`i']'" "test2/`=newfile[`i']'", replace
}

点击这里跳转到 RStata 短书平台获取附件:Stata 如何批量修改文件名

评论