如何在 R 中重命名具有特定模式的文件?
有一些 .fcs 文件data.000X 格式(其中 X = 1, 2, 3...)在目录中。
我想将每个 n 文件重命名为以下格式:exp.fcs(其中 exp 是来自向量的文本)如果文件重命名为 .fcs 文件。
换句话说:我想将文件重命名为exp.txt,其中<em>exp是一个文本,而不是连续的字母,即F、cA、K等。
例如,从:
data.0001, data.0002, data.0003, data.0004, data.0005, data.0006...
到
textF_a.fcs, textF_b.fcs, textF_c.fcs, textVv_a.fcs, textVv_b.fcs, textVv_c.fcs ...
我尝试使用 文件.重命名(来自, to) 但失败了,因为参数的长度不同(而且我不知道这意味着什么):
a <- list.files(path = ".", pattern = "data.*$")
b <- paste("data", 1:1180, ".fcs", sep = "")
file.rename(a, b)
There are some .fcs files in a data.000X format (where X = 1, 2, 3...) in a directory.
I want to rename every n file to the following format: exp.fcs (where exp is a text from a vector) if the file to be renamed is an .fcs file.
in other words: I want to rename files to exp.txt, where exp is a text and not a consecutive letter(s) i.e. F, cA, K, etc.
For example, from:
data.0001, data.0002, data.0003, data.0004, data.0005, data.0006...
to
textF_a.fcs, textF_b.fcs, textF_c.fcs, textVv_a.fcs, textVv_b.fcs, textVv_c.fcs ...
I tried to do it with file.rename(from, to) but failed as the arguments have different lengths (and I don't know what it means):
a <- list.files(path = ".", pattern = "data.*$")
b <- paste("data", 1:1180, ".fcs", sep = "")
file.rename(a, b)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据您的评论,一个问题是您的第一个文件未命名为“data.001” - 它名为“data.1”。使用这个:
它会在索引 << 之前添加最多 3 个 0(因为看起来您有 1000 多个文件,这可能会更好)。 1000,以便所有名称具有相同的宽度。如果您确实只想查看“data.001”之类的内容,请在命令中使用
%.3d
。Based on your comments, one issue is that your first file isn't named "data.001" - it's named "data.1". Use this:
It prepends up to 3 0s (since it seems you have 1000+ files, this may be better) to indices < 1000, so that all names have the same width. If you really just want to see things like "data.001", then use
%.3d
in the command.您的代码在我的机器上“有效”(“有效”是指当我创建一组文件并遵循您的过程时,重命名正确发生)。该错误可能是因为您拥有的文件数量 (
length(a)
) 与您指定的新名称数量 (length(b)
) 不同。如果事实证明这些对象确实具有相同的长度,请发回。Your code "works" on my machine ("works" in the sense that, when I created a set of files and followed your procedure, the renaming happened correctly). The error is likely that the number of files that you have (
length(a)
) is different from the number of new names that you give (length(b)
). Post back if it turns out that these objects do have the same length.与此处的(非常相似)问题一样,这个功能可能对你有用。我编写它是为了允许在 R 中进行正则表达式查找和替换。如果您使用的是 Mac,它可以检测并使用最前面的 Finder 窗口作为目标。还支持测试运行、覆盖控制和过滤大文件夹。
As with the (very similar) question here, this function might be of use to you. I wrote it to allow regex find and replace in R. If you're on a mac it can detect and use the frontmost Finder window as a target. Also supports test runs, over-write control, and filtering large folders.