【问题标题】:Rename multiple files, but only rename part of the filename in Bash重命名多个文件,但只重命名 Bash 中的部分文件名
【发布时间】:2014-01-06 14:08:31
【问题描述】:

我知道如何重命名文件等,但我遇到了麻烦。

我只需要在 for 循环中重命名 test-this

test-this.ext
test-this.volume001+02.ext
test-this.volume002+04.ext 
test-this.volume003+08.ext 
test-this.volume004+16.ext 
test-this.volume005+32.ext 
test-this.volume006+64.ext 
test-this.volume007+78.ext 

【问题讨论】:

标签: bash file-rename


【解决方案1】:

如果您将所有这些文件放在一个文件夹中,并且您使用的是 Linux,则可以使用:

rename 's/test-this/REPLACESTRING/g' *

结果将是:

REPLACESTRING.ext
REPLACESTRING.volume001+02.ext
REPLACESTRING.volume002+04.ext
...

rename 可以将命令作为第一个参数。这里的命令由四部分组成:

  1. s: 用另一个字符串替换一个字符串的标志,
  2. test-this:要替换的字符串,
  3. REPLACESTRING:要替换搜索字符串的字符串,和
  4. g:表示搜索字符串的所有匹配项都应被替换的标志,即如果文件名是test-this-abc-test-this.ext,则结果将为REPLACESTRING-abc-REPLACESTRING.ext

有关标志的详细说明,请参阅man sed

【讨论】:

  • 我这辈子的这条命令在哪里?!
  • 这个重命名的实现取决于版本,另一个答案显示相同的命令具有不同的实现语法。
  • 这不适用于 Fedora 25 中包含的重命名。我必须这样做 rename test-this REPLACESTRING *。任何人都知道在fedora中安装哪个软件包以获得答案中提到的重命名类型?
  • @Aditya 这是 Perl 重命名,prename。在 Fedora 上,我相信这个包只是被称为 prename
  • @Dylan brew install rename
【解决方案2】:

如下图使用rename

rename test-this foo test-this*

这会将文件名中的test-this 替换为foo

如果您没有rename,请使用for 循环,如下所示:

for i in test-this*
do
    mv "$i" "${i/test-this/foo}"
done

【讨论】:

  • 注意这是util-linux rename,而不是另一个答案中提到的Perl rename
  • 这似乎是我的 Centos 发行版中包含的重命名命令。显然,其他重命名对 Linux 并不通用。
  • 它们都不是通用的。这就是为什么我们需要两个单独的答案。可能答案本身应该对此更加明确和详细。
【解决方案3】:

功能

我在 OSX 上,我的 bash 没有 rename 作为内置函数。我在我的.bash_profile 中创建了一个函数,它接受第一个参数,这是文件中的一个模式,应该只匹配一次,并且不关心它后面的内容,并替换为参数 2 的文本。

rename() {
    for i in $1*
    do
        mv "$i" "${i/$1/$2}"
    done
}

输入文件

test-this.ext
test-this.volume001+02.ext
test-this.volume002+04.ext 
test-this.volume003+08.ext 
test-this.volume004+16.ext 
test-this.volume005+32.ext 
test-this.volume006+64.ext 
test-this.volume007+78.ext 

命令

rename test-this hello-there

输出

hello-there.ext
hello-there.volume001+02.ext
hello-there.volume002+04.ext 
hello-there.volume003+08.ext 
hello-there.volume004+16.ext 
hello-there.volume005+32.ext 
hello-there.volume006+64.ext 
hello-there.volume007+78.ext 

【讨论】:

  • 如果你有 Homebrew,你可以安装 renamebrew install rename
【解决方案4】:

将 index.htm 重命名为 index.html

rename [what you want to rename] [what you want it to be] [match on these files]
rename .htm .HTML *.htm

将 index.htm 重命名为 index.html 它将对文件夹中与 *.htm 匹配的所有文件执行此操作。

【讨论】:

    【解决方案5】:

    感谢您的热情和回答。我还为我找到了一个解决方案,可以在我的 linux 终端上重命名多个文件并直接添加一个小计数器。有了这个,我就有很好的机会获得更好的 SEO 名称。

    这是命令

    count=1 ; zmv '(*).jpg' 'new-seo-name--$((count++)).jpg'
    

    我还做了一个现场编码视频并发布到YouTube

    【讨论】:

      猜你喜欢
      • 2011-12-03
      • 1970-01-01
      • 2013-07-08
      • 2017-10-31
      • 2013-03-01
      • 2012-05-01
      • 1970-01-01
      • 2020-02-18
      • 2013-12-05
      相关资源
      最近更新 更多