我有一个包含许多子文件夹的文件夹,其中包含两次相同但略有不同的子文件夹:
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}”的fodler来统一这些?
我会选择 for 循环:
for f in *; do
if [ *"{Science Fiction}"* == "$f" ] && [ *"{Sci-Fi}"* == "$f" ]; then
#delete the "{Science Fiction}" part
else ...
fi
done
但这似乎不太优雅。有更清洁的解决方案吗?
答案1
您可以使用 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-Fi
于Science 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