bash 在 shell 中重命名多个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6911301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:49:29  来源:igfitidea点击:

Rename multiple files in shell

bashshell

提问by elzwhere

I have multiple files in a directory, example: linux_file1.mp4, linux_file2.mp4and so on. How do I move these files, using shell, so that the names are file1.mp4, file2.mp4and so on. I have about 30 files that I want to move to the new name.

我在一个目录中有多个文件,例如:linux_file1.mp4linux_file2.mp4等等。如何使用 shell 移动这些文件,以便名称为file1.mp4file2.mp4等等。我有大约 30 个文件要移动到新名称。

回答by sorpigal

I like mmvfor this kind of thing

我喜欢这种事情的mmv

mmv 'linux_*' '#1'

But you can also use rename. Be aware that there are commonly two renamecommands with very different syntax. One is written in Perl, the other is distributed with util-linux, so I distinguish them as "perl rename" and "util rename" below.

但您也可以使用rename. 请注意,通常有两个rename命令具有非常不同的语法。一个是用 Perl 写的,另一个是用 util-linux 分发的,所以我在下面将它们区分为“perl rename”和“util rename”。

With Perl rename:

使用 Perl 重命名:

rename 's/^linux_//' linux_*.mp4

As cweiske correctly pointed out.

正如 cweiske 正确指出的那样。

With util rename:

使用 util 重命名:

rename linux_ '' linux_*.mp4

How can you tell which rename you have? Try running rename -V; if your version is util rename it will print the version number and if it is perl rename it will harmlessly report and unknown option and show usage.

你怎么知道你有哪个重命名?尝试运行rename -V;如果您的版本是 util rename,它将打印版本号,如果是 perl rename,它将无害地报告和未知选项并显示使用情况。

If you don't have either renameor mmvand don't want to or can't install them you can still accomplish this with plain old shell code:

如果您没有renamemmv不想安装它们,您仍然可以使用普通的旧 shell 代码完成此操作:

for file in linux_*.mp4 ; do mv "$file" "${file#linux_}" ; done

This syntax will work with any POSIX sh conforming to XPG4 or later, which is essentially all shells these days.

此语法适用于任何符合 XPG4 或更高版本的 POSIX sh,现在基本上都是 shell。

回答by cweiske

$ rename 's/linux_//' linux_*.mp4

回答by dtrckd

A simple native way to do it, with directory traversal:

一种简单的原生方式,通过目录遍历

find -type f | xargs -I {} mv {} {}.txt

Will rename every file in place adding extension .txt at the end.

将重命名每个文件,在末尾添加扩展名 .txt。

And a more general cool way with parallelization:

还有一种更通用的并行化方式

find -name "file*.p" | parallel 'f="{}" ; mv -- {} ${f:0:10}trump${f:4}'

回答by Mrinal Saurabh

I was able to achieve replace filenames within directories by combining @dtrckd and @Sorpigal answers.

通过结合@dtrckd 和@Sorpigal 答案,我能够实现替换目录中的文件名。

for file in `find -name "linux_*.mp4"`; do mv "$file" "${file/linux_/}" ; done