我在一个目录中有一堆文件,这些文件是用不太令人遗憾的名字制作的.我想更改名称中的两个字符.例如,我有:
> CH:sdsn-sdfs.txt
我想删除">"并将":"更改为"_".
导致
ch_sdsn-sdfs.txt
我试着说,mv \\>ch\:* ch_*
但是没有用.
有一个简单的解决方案吗?
首先,我应该说最简单的方法是使用prename或rename命令.
自制软件包rename
,MacPorts包:renameutils
rename s/0000/000/ F0000*
Run Code Online (Sandbox Code Playgroud)
这比同等的sed命令更容易理解.
但至于理解sed命令,sed联机帮助页很有帮助.如果你运行man sed并搜索&(使用/ command搜索),你会发现它是s/foo/bar/replacementments中的特殊字符.
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.
Run Code Online (Sandbox Code Playgroud)
因此,\(.\)
匹配第一个字符,可以引用\1
.然后.
匹配下一个字符,该字符始终为0.然后\(.*\)
匹配文件名的其余部分,可以引用\2
.
替换字符串使用&
(原始文件名)将它们全部放在一起\1\2
,除了第二个字符(0)之外,它是文件名的每个部分.
恕我直言,这是一个非常神秘的方式.如果出于某种原因,重命名命令不可用并且您想使用sed进行重命名(或者您可能正在为重命名做一些过于复杂的事情?),在正则表达式中更明确地使它更具可读性.也许是这样的:
ls F00001-0708-*|sed 's/F0000\(.*\)/mv & F000\1/' | sh
Run Code Online (Sandbox Code Playgroud)
能够看到s/search/replacement /中实际发生的变化使其更具可读性.如果您不小心运行两次或其他东西,它也不会继续从文件名中吸取字符.