Shell-Script

從播放列表文件中批量重命名影片文件

  • February 29, 2020

目錄中的文件:

$ ls | sort -n

1.mp4
2 .mp4
3 .mp4
4 .mp4
5 .mp4
6 .mp4
7 .mp4
8 .mp4
9 .mp4
10 .mp4

播放列表文件中的文件名列表:

$ cat playlist.m3u8

1- Introduction-OxIDLw0M-m0.mp4
2 - How React Works-pKYiKbf7sP0.mp4
3 - React Setup (with CDN)-SAX6RMEFVM4.mp4
4 - React Components-Fis_Q3rkgtM.mp4
5 - State-yuN4EMjR4K4.mp4
6 - React Dev Tools--XQ2zCdxw0I.mp4
7 - DOM Events--ZB8I2PmiOw.mp4
8 - Changing State (and 'this')-XJzDF9bj368.mp4
9 - Intro to Forms-BVbdZ1133JU.mp4
10 - Create React App-5QwNCX3UbXc.mp4

文件名以數字開頭。如何通過播放列表文件中列出的名稱及其相應的數字重命名目錄中的文件,結果將是:

$ ls | sort -n


1- Introduction-OxIDLw0M-m0.mp4
2 - How React Works-pKYiKbf7sP0.mp4
3 - React Setup (with CDN)-SAX6RMEFVM4.mp4
4 - React Components-Fis_Q3rkgtM.mp4
5 - State-yuN4EMjR4K4.mp4
6 - React Dev Tools--XQ2zCdxw0I.mp4
7 - DOM Events--ZB8I2PmiOw.mp4
8 - Changing State (and 'this')-XJzDF9bj368.mp4
9 - Intro to Forms-BVbdZ1133JU.mp4
10 - Create React App-5QwNCX3UbXc.mp4
while read -r i ; do
   file=$(echo $i | cut -d- -f1).mp4
   if [ -e "$file" ]; then
       mv "$file" "$i"
   fi      
done < playlist.m3u8

for i in ?*.mp4; do
   mv "$i" "$(grep -xm1 "${i%.*}"'-.*\.mp4' playlist.m3u8)"
done

如果你有bash4+,這是使用mapfileaka的一種方法readarray

#!/usr/bin/env bash

shopt -s nullglob

rawfiles=(*.mp4)
mapfile -t files < <(printf '%s\n' "${rawfiles[@]}"| sort -n)
mapfile -t playlistfile < <(sort -n playlist.m3u8)

for i in "${!files[@]}"; do
  mv -v  "${files[$i]}" "${playlistfile[$i]}"
done

Linux 上的輸出

renamed '1.mp4' -> '1- Introduction-OxIDLw0M-m0.mp4'
renamed '2 .mp4' -> '2 - How React Works-pKYiKbf7sP0.mp4'
renamed '3 .mp4' -> '3 - React Setup (with CDN)-SAX6RMEFVM4.mp4'
renamed '4 .mp4' -> '4 - React Components-Fis_Q3rkgtM.mp4'
renamed '5 .mp4' -> '5 - State-yuN4EMjR4K4.mp4'
renamed '6 .mp4' -> '6 - React Dev Tools--XQ2zCdxw0I.mp4'
renamed '7 .mp4' -> '7 - DOM Events--ZB8I2PmiOw.mp4'
renamed '8 .mp4' -> '8 - Changing State (and '\''this'\'')-XJzDF9bj368.mp4'
renamed '9 .mp4' -> '9 - Intro to Forms-BVbdZ1133JU.mp4'
renamed '10 .mp4' -> '10 - Create React App-5QwNCX3UbXc.mp4'

這是單線器

rawfiles=(*.mp4); mapfile -t files < <(printf '%s\n' "${rawfiles[@]}"| sort -n); mapfile -t playlistfile < <( sort -n playlist.m3u8); for i in "${!files[@]}"; do  mv -v  "${files[$i]}" "${playlistfile[$i]}"; done

引用自:https://unix.stackexchange.com/questions/569406