首先,我应该说最简单的方法是使用 prename 或 rename 命令。
在 Ubuntu、OSX(Homebrew 包rename
、MacPorts 包p5-file-rename
)或其他带有 perl 重命名(前名)的系统上:
rename s/0000/000/ F0000*
或者在使用 util-linux-ng 重命名的系统上,例如 RHEL:
rename 0000 000 F0000*
这比等效的 sed 命令更容易理解。
但是对于理解 sed 命令,sed 联机帮助页很有帮助。如果你运行 man sed 并搜索 &(使用 / 命令搜索),你会发现它是 s/foo/bar/ 替换中的一个特殊字符。
s/regexp/replacement/
Attempt to match regexp against the pattern space. If success‐
ful, replace that portion matched with replacement. The
replacement may contain the special character & to refer to that
portion of the pattern space which matched, and the special
escapes \1 through \9 to refer to the corresponding matching
sub-expressions in the regexp.
因此,\(.\)
匹配第一个字符,它可以被 . 引用\1
。然后.
匹配下一个字符,该字符始终为 0。然后\(.*\)
匹配文件名的其余部分,可以由 . 引用\2
。
&
替换字符串使用(原始文件名)将它们放在一起,\1\2
它是文件名的每个部分,除了第二个字符是 0。
恕我直言,这是一种非常神秘的方法。如果由于某种原因重命名命令不可用,并且您想使用 sed 进行重命名(或者您正在做一些过于复杂而无法重命名的事情?),那么在您的正则表达式中更加明确会使其更具可读性。也许是这样的:
ls F00001-0708-*|sed 's/F0000\(.*\)/mv & F000\1/' | sh
能够看到 s/search/replacement/ 中实际发生的变化使其更具可读性。如果您不小心运行了两次或其他什么,它也不会继续从您的文件名中吸取字符。