如何重命名使用find命令找到的文件 [英] How do I rename files found with the find command
问题描述
我有一系列音乐文件夹.一些文件名包含一个下划线,我想删除它.
I have a series of music folders. Some of the file names contain an underscore which I would like to get rid of.
使用
find /Users/Chris/CDs -type f -name "*_*"
我发现所有带下划线的文件.
看来我可以在命令中添加-execdir mv {}
,但是不知道从那里添加什么.
我认为{}
提供完整的路径和文件名作为带下划线的文件字符串,但是我不知道如何使用sed 's/_//g'
之类的东西来删除新文件名上的_.
任何帮助将不胜感激.
I find all of the files with underscores.
it appears that I can add -execdir mv {}
to the command but do not know what to add from there.
I think {}
provides the full path and file name as a string of the file with underscores but I do not know how to use something like sed 's/_//g'
to remove the _ on the new file name.
Any help would be greatly appreciated.
推荐答案
尝试:
find /Users/Chris/CDs -type f -name "*_*" -execdir bash -c 'mv -i -- "$1" "${1//_/}"' Mover {} \;
工作原理:
-
-execdir bash -c '...' Mover {} \;
这将启动bash,并告诉它在单引号中运行该命令,并将Mover
分配给$0
,并将文件名分配给$1
.
This starts up bash and tells it to run the command in the single quotes with Mover
assigned to $0
and the file name assigned to $1
.
mv -i -- "$1" "${1//_/}"
这将重命名文件$1
.它使用bash的参数扩展功能${1//_/}
,通过删除所有下划线从$1
创建目标名称.
This renames file $1
. This uses bash's parameter expansion feature, ${1//_/}
, to create the target name from $1
by removing all underlines.
选项-i
告诉mv
在覆盖文件之前进行交互询问.
The option -i
tells mv
to ask interactively before overwriting a file.
选项--
告诉mv
没有更多选项.这是必需的,以便名称以-
开头的文件将被正确处理.
The option --
tells mv
that there are no more options. This is needed so that files whose names begin with -
will be processed correctly.
让我们从包含以下文件的目录开始:
Let's start with a directory with these files:
$ ls
1_2_3_4 a_b c_d
接下来,我们运行命令:
Next we run our command:
$ find . -type f -name "*_*" -execdir bash -c 'mv -i -- "$1" "${1//_}"' Mover {} \;
命令完成后,文件为:
$ ls
1234 ab cd
$0
的目的
在添加了错误的地方观察此命令:
The purpose of $0
Observe this command where we have added an error:
$ find . -type f -name "*_*" -execdir bash -c 'foobar -i -- "$1" "${1//_}"' Mover {} \;
Mover: foobar: command not found
请注意Mover
出现在错误消息的开头.这表明错误来自bash -c
命令内部.
Note that Mover
appears at the beginning of the error message. This signals that the error comes from within the bash -c
command.
如果将Mover
替换为-
,则会看到:
If we replace Mover
with -
, we would see:
$ find . -type f -name "*_*" -execdir bash -c 'foobar -i -- "$1" "${1//_}"' - {} \;
-: foobar: command not found
在终端中运行单个命令时,错误的根源仍然可能仍然很明显.但是,如果将此find
命令埋在一个较长的脚本中,则使用更具描述性的$0
(如Mover
或类似内容)可能会大有帮助.
When running a single command in a terminal, the source of the error may still be obvious anyway. If this find
command were buried inside a long script, however, the use of a more descriptive $0
, like Mover
or whatever, could be a big help.
这篇关于如何重命名使用find命令找到的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!