简体   繁体   English

通过脚本重命名文件

[英]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 ) 但是,您可能想看看重renameperl-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 : 这里发生了什么 :

  1. We find out all the files ending with .avi.mp4 extension. 我们find所有扩展名为.avi.mp4的文件。
  2. Since the file can contain newline characters, we make the filenames null terminated using print0 option of the find . 由于该文件可以包含换行符,我们做文件名null进行终止print0该选项的find
  3. This output is piped into while loop where we are ready to parse the files. 此输出通过管道传递到while循环中,在此我们可以解析文件。
  4. Setting the delimiter -d option of the read to null( '' ) command we parse each of the null terminated filenames. 设置分隔符-d中的选项read为null( '' )命令,我们分析每个空终止的文件名。
  5. Finally we use parameter expansion/substitution to get rid of the .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. 参见参考文献1。

References : 参考文献:

  1. Shell parameter expansion Shell参数扩展
  2. Move manual 手动移动
  3. Why use while instead of for? 为什么用while代替for?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM