Удаление одинаковых файлов из папок

выключение с помощью:

nmcli networking off

затем снова с помощью:

nmcli networking on

Или

nmcli connection reload

Или

nmcli con down eth0

nmcli con up eth0

Или вы можете использоватьnmtui

nmtui— это текстовый пользовательский интерфейс для управления сетевым менеджером. Когда мы запускаем nmtui, он открывает текстовый пользовательский интерфейс, через который мы можем добавлять, изменять и удалять соединения.

0
23.01.2021, 14:27
2 ответа

Вот как вы это делаете, сравнивая хэш всех файлов.

Метод 1 (рекомендуется):

Спасибо Кусалананде за предложение использовать join, упрощающее задачу. Вы можете использовать следующие команды. Обратите внимание, что если в имени любого файла есть пробелы, это не сработает.

# DIR1 is the main directory
# DIR2 is from where files will get deleted. Change the values accordingly
DIR1="$PWD"
DIR2="$HOME"

find $DIR1 -type f | xargs md5sum 2>/dev/null | sort > /tmp/m1
find $DIR2 -type f | xargs md5sum 2>/dev/null | sort > /tmp/m2

join /tmp/m1 /tmp/m2 > /tmp/m3
cat /tmp/m3 | cut -d ' ' -f3 | xargs rm -f

# To delete empty directories
find $DIR2 -type d -empty -delete

Метод 2:

Здесь мы просто повторно вычисляем хэш всех файлов в обоих каталогах и удаляем файл, если они совпадают.

# DIR1 is the main directory
# DIR2 is from where files will get deleted.
DIR1="$PWD"
DIR2="$HOME"

# Take a file from $DIR1 and check for it in $DIR2
for i in $DIR1/*; do
    HASH=$(md5sum $i 2>/dev/null | cut -d ' ' -f1 )
    if [ "$HASH" ]; then
        for j in $DIR2/*; do
            HASH2=$(md5sum $j | cut -d ' ' -f1)
            if [ "$HASH" = "$HASH2" ]; then
                # Delete files from $DIR2
                rm "$j"
            fi
        done
    fi
done
1
18.03.2021, 22:34

Сfdupes:

fdupes -drN dir1 dir2

Это приведет к удалению всего в двух каталогах, которые найдены более одного раза. Первая найденная копия любого дубликата сохраняется.

С длинными опциями:

fdupes --delete --recurse --noprompt dir1 dir2

Обратите внимание, что это также удаляет файлы в dir1, которые являются дубликатами других файлов в том же каталоге.

В системе с инструментами GNU вы можете обойти проблему с удалением дубликатов в dir1, если сделаете это самостоятельно:

#!/bin/sh

dir1=somedir
dir2=someotherdir

sums1=$(mktemp)
sums2=$(mktemp)

# Remove temporary files when done.
trap 'rm -f "$sums1" "$sums2"' EXIT

# Calculate checksums for first directory, extract only the checksums
# themselves and sort them (removing duplicate checksums).
find "$dir1" -type f -exec md5sum -z {} + |
cut -z -c -32 |
sort -z -u -o "$sums1"

# Calculate the checksums for the second directory, and sort them.
find "$dir2" -type f -exec md5sum -z {} + |
sort -z -o "$sums2"

# Join the files on the first column, extract the pathnames for the
# files in the second directory that have the same checksum as files in
# the first directory, and delete these files.
join -z "$sums1" "$sums2" |
cut -z -c 34- |
xargs -0 rm -f


# Optionally, delete empty directories in the second directory
# find "$dir2" -type d -empty -delete

Приведенный выше код дополнительно пытается убедиться, что любое допустимое имя файла обрабатывается должным образом, передавая пути в виде списков, завершающихся -nul.


Укороченныйbash-вариант приведенного выше скрипта:

#!/bin/bash

dir1=somedir
dir2=someotherdir

join -z \
    <(find "$dir1" -type f -exec md5sum -z {} + | cut -z -c -32 | sort -z -u)  \
    <(find "$dir2" -type f -exec md5sum -z {} + | sort -z) |
cut -z -c 34- |
xargs -0 rm -f
1
18.03.2021, 22:34

Теги

Похожие вопросы