如何使用模式重命名資料夾中的所有文件

如何使用模式重命名資料夾中的所有文件

我有一堆文件,例如:

bla.super.lol.S01E03.omg.bbq.mp4
bla.super.lol.S01E04.omg.bbq.mp4
bla.super.lol.s03e12.omg.bbq.mp4

我需要將它們全部重命名為:

s01e03.mp4
s01e04.mp4
s03e12.mp4

我嘗試這樣做,for file in *; do mv $file ${file%%\.omg*}; done但它僅刪除 S01E01 之後的部分,而不是之前的部分,所以請幫忙

答案1

renameprename):

rename -n 's/^bla\.super\.lol\.[sS](\d+)[eE](\d+)\..*(\.mp4$)/s$1e$2$3/' *.mp4

-n是否進行空運行,如果您對潛在的重命名感到滿意,只需刪除-n即可進行實際的重命名:

rename 's/^bla\.super\.lol\.[sS](\d+)[eE](\d+)\..*(\.mp4$)/s$1e$2$3/' *.mp4

例子:

$ ls -1
bla.super.lol.S01E03.omg.bbq.mp4
bla.super.lol.S01E04.omg.bbq.mp4
bla.super.lol.s03e12.omg.bbq.mp4

$ rename -n 's/^bla\.super\.lol\.[sS](\d+)[eE](\d+)\..*(\.mp4$)/s$1e$2$3/' *.mp4
bla.super.lol.S01E03.omg.bbq.mp4 renamed as s01e03.mp4
bla.super.lol.S01E04.omg.bbq.mp4 renamed as s01e04.mp4
bla.super.lol.s03e12.omg.bbq.mp4 renamed as s03e12.mp4

答案2

#!/bin/bash
IFS="\n"                               # Handle files with spaces in the names
for file in *.mp4; do
    newfile="${file/bla.super.lol./}"  # Strip the prefix you don't want
    newfile="${newfile/S/s}"           # Change the first S to an s
    newfile="${newfile/E/e}"           # Change the first E to an e
    newfile="${newfile.%omg.bbq*}"     # Strip the suffix you don't want
    newfile="${newfile}.mp4}"          # Tack on the file extension again
done
if [[ "$file" == "$newfile" ]]; then
    echo "Not renaming $file - no change decreed."
elif [[ -f "$newfile" ]]; then
    echo "Not renaming $file - $newfile already exists."
else
    mv -- "$file" "$newfile"           # Make the change
fi

答案3

把事情簡單化..

rename 's/.*\.(\w+)\.omg\..*mp4$/\L$1.mp4/' *.mp4

例子:

$ echo 'bla.super.lol.S01E03.omg.bbq.mp4' | perl -pe 's/.*\.(\w+)\.omg\..*mp4$/\L$1.mp4/'
s01e03.mp4

相關內容