gpt4 book ai didi

linux - 在 Linux 中使用 Bash 获取文件名并删除同名文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:53:57 24 4
gpt4 key购买 nike

我正在尝试查看目录并根据文件名删除重复文件。我使用以下代码执行此操作:

    for i in `seq 1 10`;
do
rm "$d"/*\($i\).mp3
done

这会保留 song.mp3 并删除 song(1).mp3、song(2).mp3 等等,最多重复 10 次。

但是,我意识到原始文件不是没有附加重复 (1).mp3 或 (2).mp3 的文件,而是重复次数最多(最早修改日期)的文件,在这种情况下会是歌曲(2).mp3。这是因为出于某种原因,我正在使用的程序将原始文件重命名为 song(1).mp3,并将最新文件命名为 song.mp3。

所以在上述情况下我想做的是删除 song.mp3 和 song(1).mp3 以及 mv song(2).mp3 到 song.mp3 以便它的修改日期不会改变。

在此先感谢您的帮助。

最佳答案

此解决方案适用于所有文件,而不仅仅是手动指定的文件,如 d="song"
。我希望代码注释是 self 解释的:

# Iterate through all file name prefixes of candiates
while read prefix ; do

[[ -z "$prefix" ]] && continue

# Get the oldest file. (The one with the largest suffix value for this prefix)
oldest=$(find -maxdepth 1 -type f -name "$prefix(*).mp3" | sort -t\( -k2r | head -n1)

# Overwrite the newest with the oldest file.
mv -v "$oldest" "$prefix.mp3"

# Delete the files between oldest and newest
rm -fv "$prefix(*.mp3"

done <<< $(find -maxdepth 1 -type f -regex '.*([0-9]+).mp3' -printf "%f" | cut -f 1 -d\( | uniq)

关于linux - 在 Linux 中使用 Bash 获取文件名并删除同名文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24005501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com