Bash

重命名文件夾中的所有文件刪除重複的字元串部分

  • January 10, 2016

我有一個包含許多子文件夾的文件夾,其中包含兩倍但略有不同:

Movie1 {Action}{Adventure}{Sci-Fi}{Thriller}{Science Fiction}/
Movie2 {Action}{Adventure}{Thriller}{Science Fiction}/
Movie3 {Action}{Adventure}{Thriller}{Sci-Fi}}/
Movie4 {Action}{Adventure}{Thriller}/

如何通過刪除“{Sci-Fi}”已經存在的“{Science Fiction}”部分來統一這些,重命名不包含“{Sci-Fi}”但僅包含“{Science Fiction}”的文件?

我會去一個for循環:

for f in *; do
 if [ *"{Science Fiction}"* == "$f" ] && [ *"{Sci-Fi}"* == "$f" ]; then
   #delete the "{Science Fiction}" part
 else ...
 fi
done

但這似乎不是很優雅。有更清潔的解決方案嗎?

您可以使用 sed 從字元串中刪除重複項:

for f in *; do
 r=$(echo $f | sed -r "s/(.*)(\{Sci-Fi\}|\{Science Fiction\})(.*)(\{Sci-Fi\}|\{Science Fiction\})(.*)/\1\2\3\5/g");
 echo $r;
done

如果您喜歡輸出,請替換echo $f為。mv "$f" "$r"

上面的sed行將取第一個匹配的單詞並刪除第二個,如果你想總是優先Sci-FiScience Fiction,即使只Science Fiction存在,你可以分兩步完成:

for f in *; do
 r=$(echo $f | sed "s/{Science Fiction}/{Sci-Fi}/");
 s=$(echo $r | sed -r "s/(.*)(\{Sci-Fi\})(.*)(\{Sci-Fi\})(.*)/\1\2\3\5/g");
 if [ "$f" != "$s" ]; then
   echo "moving " $f " to " $s
 fi
done

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