首先,我应该说最简单的方法是使用prename或rename命令。
Homebrew软件包rename
,MacPorts软件包renameutils
:
rename s/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)以外的部分。
在我看来,这是一种相当神秘的方法。如果由于某些原因无法使用rename命令,并且您想要使用sed进行重命名(或者可能正在做一些过于复杂的操作),则更明确地编写您的正则表达式将使其更易读。也许像这样:
ls F00001-0708-*|sed 's/F0000\(.*\)/mv & F000\1/' | sh
能够看到实际变化的内容,使得代码更易读。此外,如果不小心运行两次或其他情况下,它也不会从文件名中吞噬字符。