Linux 一个用于重命名一堆文件的衬垫

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9877103/
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-08-06 05:25:14  来源:igfitidea点击:

One liner to rename bunch of files

linuxfilerename

提问by Jean

I was looking for a linux command line one-liner to rename a bunch of files in one shot.

我正在寻找一个 linux 命令行单行程序来一次性重命名一堆文件。

pattern1.a  pattern1.b pattern1.c ...

Once the command is executed I should get

一旦命令被执行,我应该得到

pattern2.a  pattern2.b pattern2.c ...

回答by Kerrek SB

for i in pattern1.*; do mv -- "$i" "${i/pattern1/pattern2}"; done

Before you run it, stick an echoin front of the mvto see what it woulddo.

在运行它之前,echo在 前面贴一个,mv看看它做什么。

回答by ghoti

Plenty of ways to skin this cat. If you'd prefer your pattern to be a regex rather than a fileglob, and you'd like to do the change recursively you could use something like this:

有很多方法可以给这只猫剥皮。如果您希望您的模式是正则表达式而不是 fileglob,并且您希望以递归方式进行更改,则可以使用以下内容:

find . -print | sed -ne '/^\.\/pattern1\(\..*\)/s//mv "&" "pattern2"/p'

As Kerrek suggested with his answer, this one first shows you what it would do. Pipe the output through a shell (i.e. add | shto the end) once you're comfortable with the commands.

正如 Kerrek 在他的回答中所建议的那样,这个首先向您展示了它会做什么。| sh一旦您对命令感到满意,就将输出通过 shell(即添加到末尾)。

This works for me:

这对我有用:

[ghoti@pc ~]$ ls -l foo.*
-rw-r--r--  1 ghoti  wheel  0 Mar 26 13:59 foo.php
-rw-r--r--  1 ghoti  wheel  0 Mar 26 13:59 foo.txt
[ghoti@pc ~]$ find . -print | sed -ne '/^\.\/foo\(\..*\)/s//mv "&" "bar"/p'
mv "./foo.txt" "bar.txt"
mv "./foo.php" "bar.php"
[ghoti@pc ~]$ find . -print | sed -ne '/^\.\/foo\(\..*\)/s//mv "&" "bar"/p' | sh
[ghoti@pc ~]$ ls -l foo.* bar.*
ls: foo.*: No such file or directory
-rw-r--r--  1 ghoti  wheel  0 Mar 26 13:59 bar.php
-rw-r--r--  1 ghoti  wheel  0 Mar 26 13:59 bar.txt
[ghoti@pc ~]$ 

回答by ghoti

If you happen to be using Linux, you may also have a perl script at /usr/bin/rename which cane rename files based on more complex patterns than shell globbing permits.

如果您碰巧使用 Linux,您可能还有一个位于 /usr/bin/rename 的 perl 脚本,它可以根据比 shell globbing 允许的更复杂的模式重命名文件。

The /usr/bin/rename on one of my systems is documented here. It could be used like this:

我的其中一个系统上的 /usr/bin/rename 记录在此处。它可以像这样使用:

rename "s/pattern1/pattern2/" pattern1.*

A number of other Linux environmentsseem to have a different renamethat might be used like this:

许多其他 Linux 环境似乎有一个不同的rename可以这样使用:

rename pattern1 pattern2 pattern1.*

Check man renameon your system for details.

检查man rename您的系统以获取详细信息。