R中的文件扩展名重命名

时间:2016-11-23 01:41:51

标签: r text-mining file-rename

我只是想将文件扩展名更改为.doc。我正在尝试下面的代码,但它不起作用。怎么会?我正在使用here

中的说明
Dim query As String = "
SELECT * FROM (
SELECT TOP 10     T.name TableName, i.Rows NumberOfRows
FROM        sys.tables T
JOIN        sys.sysindexes I ON T.OBJECT_ID = I.ID
WHERE       indid IN (0,1)
ORDER BY    i.Rows DESC, T.name ASC
) AS TableA
ORDER BY TableName ASC
"

我得到的输出是:

vbCrLf & "                SELECT * FROM (" & vbCrLf & "                SELECT TOP 10     T.name TableName, i.Rows NumberOfRows" & vbCrLf & "                FROM        sys.tables T" & vbCrLf & "                JOIN        sys.sysindexes I ON T.OBJECT_ID = I.ID" & vbCrLf & "                WHERE       indid IN (0,1)" & vbCrLf & "                ORDER BY    i.Rows DESC, T.name ASC" & vbCrLf & "                ) AS TableA" & vbCrLf & "                ORDER BY TableName ASC" & vbCrLf & "                "

1 个答案:

答案 0 :(得分:3)

这更容易。在这里,我们首先创建10个文件(在shell中):

$ for i in 0 1 2 3 4 5 6 7 8 9; do touch file${i}.log; done

然后在R中它实际上只是三个矢量化操作:

files <- list.files(pattern="*.log")
newfiles <- gsub(".log$", ".doc", files)
file.rename(files, newfiles)

我们读取文件名,一次对所有文件名进行转换(将.log替换为.doc)并从旧名称一次重命名所有文件新的名字。

这将为每个隐式重命名回显TRUE

edd@max:/tmp/filerename$ Rscript renameFiles.R 
 [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
edd@max:/tmp/filerename$ ls
file0.doc  file1.doc  file2.doc  file3.doc  file4.doc  file5.doc  
file6.doc  file7.doc  file8.doc  file9.doc  renameFiles.R
edd@max:/tmp/filerename$ 

编辑:以下是在R中执行所有操作的更明确的演练:

edd@max:/tmp/filerename/new$ ls                    ## no files here
renameFiles.R
edd@max:/tmp/filerename/new$ cat renameFiles.R     ## code we will run

options(width=50)
ignored <- sapply(1:10, function(n) write.csv(n, file=paste0("file", n, ".log")))
files <- list.files(pattern="*.log")
print(files)

newfiles <- gsub(".log$", ".doc", files)
file.rename(files, newfiles)

files <- list.files(pattern="*.doc")
print(files)
edd@max:/tmp/filerename/new$ Rscript renameFiles.R  ## running it
 [1] "file10.log" "file1.log"  "file2.log" 
 [4] "file3.log"  "file4.log"  "file5.log" 
 [7] "file6.log"  "file7.log"  "file8.log" 
[10] "file9.log" 
 [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[10] TRUE
 [1] "file10.doc" "file1.doc"  "file2.doc" 
 [4] "file3.doc"  "file4.doc"  "file5.doc" 
 [7] "file6.doc"  "file7.doc"  "file8.doc" 
[10] "file9.doc" 
edd@max:/tmp/filerename/new$