「重複」ファイルシェルスクリプトの削除

「重複」ファイルシェルスクリプトの削除

次のファイルのリストがあります。

file.txt
file (1).txt
file (2).txt
file (7).txt

など。

そのうち大きい方(数字)が最後に更新されたファイルですが、中間数字の一部が欠落している可能性があり、ディレクトリに別のファイルがある可能性があります。

「重複」ファイルがあるかどうかを確認し、その場合は内容をにコピーしてfile (maxnumer).txtすべてのfile.txtファイルを削除しますfile (*).txt

ls -t file*(*)*.txtリストをリストしてから繰り返してみましたが、forエラー()が発生しましたlsbash:syntax error near unexpected token '('

ベストアンサー1

タイムスタンプが信頼できないと仮定すると、ファイル名の末尾に括弧内に最大数のファイルを見つけようとします。

この方法:

#!/bin/sh

prefix=$1

if [ -z "$prefix" ]; then
    printf 'Usage: %s prefix [ suffix ]\n' "$0" >&2
    exit 1
fi

suffix=$2

for filename in "$prefix ("*")$suffix"; do
    [ ! -f "$filename" ] && continue

    num=${filename##*\(}    # "file (xx).txt" --> "xx).txt"
    num=${num%\)*}          # "xx).txt" --> "xx"

    # if no max number yet, or if current number is higher, update max
    if [ -z "$max" ] || [ "$num" -gt "$max" ]; then
        max=$num
    fi
done

# if we have a max number, use it to rename the file and then remove the other files
if [ -n "$max" ]; then
    printf 'Would move %s to %s\n' "$prefix ($max)$suffix" "$prefix$suffix"
    # mv "$prefix ($max)$suffix" "$prefix$suffix"
    printf 'Would remove %s\n' "$prefix ("*")$suffix"
    # rm "$prefix ("*")$suffix"
else
    printf 'Found no files matching "%s (*)%s"\n' "$prefix" "$suffix"
fi

実行してください:

$ tree
.
|-- file (1).txt
|-- file (2).txt
|-- file (7).txt
|-- file.list
|-- file.txt
`-- script.sh

0 directory, 6 files

$ sh script.sh file .txt
Would move file (7).txt to file.txt
Would remove file (1).txt
Would remove file (2).txt
Would remove file (7).txt

(コメントを削除しmvrm実際にファイルを編集してみてください)

file (2) (30).txtすべてのファイル名が整数のパターンに従うと仮定しているため(これらも一致します)などのファイル名は失敗します。prefix (NN)suffixNN

おすすめ記事