如何在 Unix 中的单个命令或脚本中重命名多个文件?

Udh*_*mar 65 linux shell-script rename

我有以下文件列表

aro_tty-mIF-45875564pmo_opt
aro_tty-mIF-45875664pmo_opt
aro_tty-mIF-45875964pmo_opt
aro_tty-mIF-45875514pmo_opt
aro_tty-mIF-45875524pmo_opt
Run Code Online (Sandbox Code Playgroud)

我需要重命名为

aro_tty-mImpFRA-45875564pmo_opt
aro_tty-mImpFRA-45875664pmo_opt
aro_tty-mImpFRA-45875964pmo_opt
aro_tty-mImpFRA-45875514pmo_opt
aro_tty-mImpFRA-45875524pmo_opt
Run Code Online (Sandbox Code Playgroud)

Mar*_*ick 86

大多数标准 shell 提供了一种在 shell 变量中进行简单文本替换的方法。http://tldp.org/LDP/abs/html/parameter-substitution.html解释如下:

${var/Pattern/Replacement}

First match of Pattern, within var replaced with Replacement.
Run Code Online (Sandbox Code Playgroud)

因此,使用此脚本遍历所有适当的文件并重命名每个文件:

for file in aro_tty-mIF-*_opt
do
    mv -i "${file}" "${file/-mIF-/-mImpFRA-}"
done
Run Code Online (Sandbox Code Playgroud)

我添加了一个 -i 选项,因此您有机会确认每个重命名操作。与往常一样,在进行大量重命名或删除之前,您应该备份所有文件。

  • @YngvarKristiansen 这些字符串是原始海报使用的文件名的一部分。它们不是命令选项或类似的东西。 (2认同)

Jos*_* R. 20

如果你没有 Perl 的rename

perl -e '
FILE:for $file (@ARGV){
        ($new_name = $file) =~ s/-mIF-/-mImpFRA-/
        next FILE if -e $new_name;
        rename $file => $new_name
}' *_opt
Run Code Online (Sandbox Code Playgroud)

如果你有Perl的rename

rename 's/-mIF-/-mImpFRA-/' *_opt
Run Code Online (Sandbox Code Playgroud)


Rma*_*ano 17

在尝试像下面这样的复杂命令之前,请备份您的文件。你永远不知道错别字(我的或你的)会导致什么。

使用mv(正如您在评论中所问的那样 ---rename正如另一个答案中所建议的那样可能更安全,尤其是如果您的文件名中可以​​有空格或奇怪的字符)某种风格

for f in *_opt; do
    a="$(echo $f | sed s/-mIF-/-mImpFRA-/)"
    mv "$f" "$a"
done
Run Code Online (Sandbox Code Playgroud)