[英]Renaming Files Through Script
I have a few files that are incorrectly named (with the extension added twice to the end). 我有一些文件名不正确(扩展名末尾添加了两次)。 I was trying to write a bash script that would scan the directory and rename them, but it throws an error of:
我试图编写一个bash脚本,该脚本将扫描目录并重命名它们,但是会引发以下错误:
cannot move '/var/random/file/file1.avi.mp4' to '{/var/random/file/file1.avi.mp4%.avi.mp4}.mp4': No such file or directory
无法将“ /var/random/file/file1.avi.mp4”移动到“ {/var/random/file/file1.avi.mp4%.avi.mp4}.mp4”:没有这样的文件或目录
I just want to properly rename the file extension, and am not sure where the error comes into play. 我只想适当地重命名文件扩展名,并且不确定该错误在哪里起作用。 For example, the error above, should have a file extension of .mp4.
例如,上述错误的文件扩展名应为.mp4。 Below is my script, if someone could assist, I would be in debted...
以下是我的剧本,如果有人可以提供帮助,我将无所适从...
#/bin/sh
for file in $(find /var/random/ -type f -name "*.avi.mp4"); do
mv "$file" "{$file%.avi.mp4}.mp4"
done
You have a typo in your variable expansion: 您的变量扩展中有一个错字:
"{$file%.avi.mp4}.mp4"
should have been: 本来应该:
"${file%.avi.mp4}.mp4"
However you might want to take a look at rename
( perl-rename
) 但是,您可能想看看重
rename
( perl-rename
)
perl-rename 's/[^.]+\.(?=[^.]+$)//' /var/random/*/*.avi.mp4
The regex will remove the second to last extension in file names: 正则表达式将删除文件名中倒数第二个扩展名:
/path/to/file/foo.bar.baz -> /path/to/file/foo.baz
find . -type f -name "*.avi.mp4" -print0 | while read -rd '' filename
do
if [ -e "${filename%.avi.mp4}.mp4" ]
then
mv --backup "${filename}" "${filename%.avi.mp4}.mp4"
#doing the backup only if the destination file exists to save space.
else
mv "${filename}" "${filename%.avi.mp4}.mp4"
fi
done
What happened here : 这里发生了什么 :
find
out all the files ending with .avi.mp4
extension. find
所有扩展名为.avi.mp4
的文件。 print0
option of the find
. print0
该选项的find
。 -d
option of the read
to null( ''
) command we parse each of the null terminated filenames. -d
中的选项read
为null( ''
)命令,我们分析每个空终止的文件名。 .avi.mp4
at end of each file and append a .mp4
to each file at the mv
phase. .avi.mp4
,并在mv
阶段将.mp4
附加到每个文件。 See reference 1. References : 参考文献:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.