本文介绍了递归批量重命名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个文件夹,其中包含一些我想重命名的文件

I have several folders with some files that I would like to rename from

Foo'Bar - Title

Title

我正在使用OS X 10.7.我看过其他解决方案,但是都没有很好地解决递归问题.

I'm using OS X 10.7. I've looked at other solutions, but none that address recursion very well.

有什么建议吗?

推荐答案

尝试一下:

ls -1 * | while read f ; do mv "$f" "`echo $f | sed 's/^.* - //'`" ; done

我建议您在运行mv之前在mv之前添加echo,以确保命令看起来正常.而且正如abarnert在评论中指出的那样,此命令一次仅适用于一个目录.

I recommend you to add a echo before mv before running it to make sure the commands look ok. And as abarnert noted in the comments this command will only work for one directory at a time.

各种命令的详细说明:

ls -1 *将为当前目录(. -files除外)中的每个文件(和目录)输出一行.因此,它将扩展为ls -1 file1 file2 ...-1ls告诉它仅列出文件名,每行列出一个文件.

ls -1 * will output a line for each file (and directory) in the current directory (except .-files). So this will be expanded in to ls -1 file1 file2 ..., -1 to ls tells it to list the filename only and one file per line.

然后将输出传递到while read f ; ... ; done中,该循环将在read f返回零的同时循环,直到返回文件末尾为止. read f一次从标准输入(在本例中为ls -1 ...的输出)中读取一行,并将其存储在指定的变量中,在本例中为f.

The output is then piped into while read f ; ... ; done which will loop while read f returns zero, which it does until it reaches end of file. read f reads one line at a time from standard input (which in this case is the output from ls -1 ...) and store it in the the variable specified, in this case f.

在while循环中,我们运行带有两个参数的mv命令,第一个"$f"作为源文件(注意引号来处理带空格的文件名等),第二个目标文件名使用sed和`(反引号)做所谓的命令替换,它将在反引号内调用命令,并用标准输出的输出替换.

In the while loop we run a mv command with two arguments, first "$f" as the source file (note the quotes to handle filenames with spaces etc) and second the destination filename which uses sed and ` (backticks) to do what is called command substitution that will call the command inside the backticks and be replaced it with the output from standard output.

echo $f | sed 's/^.* - //'将当前文件$f用管道输送到sed中,该文件将与正则表达式匹配并进行替换(s/中的s),并将结果输出到标准输出中.正则表达式为^.* -,它将从字符串^的开头(称为锚定)开始,然后匹配任何字符.*,后跟-,然后将其替换为空字符串(//之间的字符串)

echo $f | sed 's/^.* - //' pipes the current file $f into sed that will match a regular expression and do substitution (the s in s/) and output the result on standard output. The regular expression is ^.* - which will match from the start of the string ^ (called anchoring) and then any characters .* followed by - and replace it with the empty string (the string between //).

这篇关于递归批量重命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 19:11
查看更多