2つのファイルサイズを比較し、小さいファイルを削除します。

2つのファイルサイズを比較し、小さいファイルを削除します。

2つのファイルのうち小さい方を削除する方法を探しています。私の映画ライブラリで重複したファイルを見つける方法を見つけましたが、今は小さなファイルを削除する必要があります。

bash - 拡張子に関係なく、同じ名前のすべてのファイルを検索する

もちろん、いくつかの「問題」があります。リストの現在の出力には拡張子はありません。

たとえば、

root@fs:ls * |  awk '!/.srt/'  | sed 's/.\{4\}$//' | sort | uniq -d
Captain Fantastic (2016)
The Hurt Locker (2008)
The Warriors (1979)

Captain Fantastic (2016).*両方のファイルの拡張子が異なるため、戻って2つのファイルを名前と比較する方法が必要です。 (すべてのファイルは同じフォルダにあります)

これは質問の範囲をわずかに超えています。

また、ファイルが存在することを確認したいと思いますFILENAME.srt。その場合は、何も実行せず、手動確認のためにファイル名をログに保存します。 (どのファイルsrtが同期されるかを調べる必要があります)。

ベストアンサー1

提案:

#!/bin/sh

# Look at filenames in current directory and generate list with filename
# suffixes removed (a filename suffix is anything after the last dot in
# the file name). We assume filenames that does not contain newlines.
# Only unique prefixes will be generated.
for name in ./*; do
        [ ! -f "$name" ] && continue # skip non-regular files
        printf '%s\n' "${name%.*}"
done | sort -u |
while IFS= read -r prefix; do
        # Set the positional parameters to the names matching a particular prefix.
        set -- "$prefix"*

        if [ "$#" -ne 2 ]; then
                printf 'Not exactly two files having prefix "%s"\n' "$prefix" >&2
                continue
        fi

        # Check file sizes and remove smallest.
        if [ "$( stat -c '%s' "$1" )" -lt "$( stat -c '%s' "$2" )" ]; then
                # First file is smaller
                printf 'Would remove "%s"\n' "$1"
                echo rm "$1"
        else
                # Second file is smaller, or same size
                printf 'Would remove "%s"\n' "$2"
                echo rm "$2"
        fi
done

これはGNUを想定していますstat

おすすめ記事