<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Linux Forum &mdash; Дубликаты]]></title>
	<link rel="self" href="https://linuxforum.ru/extern.php?action=feed&amp;tid=30982&amp;type=atom" />
	<updated>2013-11-03T10:31:34Z</updated>
	<generator>PunBB</generator>
	<id>https://linuxforum.ru/viewtopic.php?id=30982</id>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=373389#p373389" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>-=Serj=- пишет:</cite><blockquote><p>Хотя, неужели нельзя обеспечить безопасность? Тем же bash, perl или php можно дров наломать...</p></blockquote></div><p>это не мои сервера. Тамошние админы считают, что от perl&#039;а вреда нет, а вот от питона есть. Школьники шалят. А перловку им не осилить.</p><div class="quotebox"><cite>-=Serj=- пишет:</cite><blockquote><p>А с третьей стороны, если ты сисадмин, то, хотя бы, основы баш знать, наверное, должен. Мы же python с bash сравниваем, а не с командами?</p></blockquote></div><p>я не понимаю, как сисадмин умудрился не знать команду find??? Да ну и что, что он умеет на каком-то brainfuck&#039;е писать скрипты для поиска?</p><p>При чём тут именно bash? Я про find говорил, а не про bash, а вы занимаетесь демагогией, пытаясь перевести стрелки на спор bash vs python.</p><p>Если задача решаема одной командой(find в данном случае), то и решать нужно этой командой, а не городить кривые велосипеды с квадратными колёсами на питоне.</p>]]></content>
			<author>
				<name><![CDATA[drBatty]]></name>
				<uri>https://linuxforum.ru/profile.php?id=86</uri>
			</author>
			<updated>2013-11-03T10:31:34Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=373389#p373389</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=372574#p372574" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>-=Serj=- пишет:</cite><blockquote><p>Anatoly2012, ... как-то так) :</p></blockquote></div><p>Все отлично работает!!!&nbsp; <img src="https://linuxforum.ru/img/smilies/bp.gif" alt="bp" />&nbsp; Еще раз спасибо огромное!&nbsp; <img src="https://linuxforum.ru/img/smilies/bs.gif" alt="bs" />&nbsp; Все сделал, предоволен... За паузу простите, работа...</p><p>В скрипте немножко подправил: &quot;next&quot; на &quot;-&quot;, &quot;yes&quot; на &quot;y&quot;, &quot;no&quot; на &quot;n&quot;, и все быстро получилось. Когда попадались два-три дубликата, то meld&#039;ом сравнивал обе директории и одну из них удалял.</p><p>P.S. Можно было бы добавить в скрипт строку завершения, например: &quot;поиск завершен&quot;, а то, если нет дубликатов в файле скрипт исчезает, - сразу и не поймешь чего это.</p>]]></content>
			<author>
				<name><![CDATA[Anatoly2012]]></name>
				<uri>https://linuxforum.ru/profile.php?id=26712</uri>
			</author>
			<updated>2013-10-30T07:40:59Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=372574#p372574</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=370364#p370364" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>drBatty пишет:</cite><blockquote><p>Опыт говорит мне, что на некоторых серверах в некоторых продакшенах питона тупо НЕТ. Что вы станете делать в таком практическом случае?</p></blockquote></div><p>Ну, это аргумент, да... Хотя, неужели нельзя обеспечить безопасность? Тем же bash, perl или php можно дров наломать...<br />А с третьей стороны, если ты сисадмин, то, хотя бы, основы баш знать, наверное, должен. Мы же python с bash сравниваем, а не с командами?</p>]]></content>
			<author>
				<name><![CDATA[-=Serj=-]]></name>
				<uri>https://linuxforum.ru/profile.php?id=16175</uri>
			</author>
			<updated>2013-10-17T05:46:33Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=370364#p370364</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=370358#p370358" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>-=Serj=- пишет:</cite><blockquote><p>к сожалению, у меня не хватает умения для дальнейшего развития демагогии.</p></blockquote></div><p>кроме демагогии есть опыт. Опыт говорит мне, что на некоторых серверах в некоторых продакшенах питона тупо НЕТ. Что вы станете делать в таком практическом случае?</p>]]></content>
			<author>
				<name><![CDATA[drBatty]]></name>
				<uri>https://linuxforum.ru/profile.php?id=86</uri>
			</author>
			<updated>2013-10-17T05:10:39Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=370358#p370358</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=370271#p370271" />
			<content type="html"><![CDATA[<p><strong>drBatty</strong>, к сожалению, у меня не хватает умения для дальнейшего развития демагогии.</p><p><strong>Anatoly2012</strong>, если извращённо, то как-то так) :<br /></p><div class="codebox"><pre><code>#!/usr/bin/env python
#_*_ coding: utf-8 _*_

import os
import hashlib
import sys

ignore_list = [&#039;.gif&#039;, &#039;.js&#039;, &#039;.HLP&#039;, &#039;.tif&#039;, &#039;.css&#039;, &#039;.ico&#039;, &#039;.INF&#039;, &#039;.ini&#039;, &#039;.PFB&#039;]

try:
    work_path = sys.argv[1]
except:
    work_path = &#039;.&#039;

md5_dic = {}
dirTree = os.walk(work_path)

def getMd5sum(fname):
    with open(fname) as f:
        return hashlib.md5(f.read()).hexdigest()

for dirPath, dirNames, Files in dirTree:
    for f in Files:
        if os.path.splitext(f)[1] in ignore_list:
            continue
        full_name = os.path.join(os.path.abspath(dirPath), f)
        md5 = getMd5sum(full_name)
        if md5 not in md5_dic:
            md5_dic[md5] = []
            md5_dic[md5].append(full_name)
        else:
            md5_dic[md5].append(full_name)
            
md5_dic = dict((key, val) for key, val in md5_dic.items() if len(val) &gt; 1)

group_num = len(md5_dic)
print(&#039;Number of groups duplicate files: %d&#039; % group_num)
i = 1
for key, val in md5_dic.items():
    print(&#039;\nGroup %d of %d:&#039; % (i, group_num))
    for f in val:
        print(&#039;%5d %s&#039; % (val.index(f) + 1, f))
    print(&#039;&#039;)
    while True:
        answer = raw_input(&#039;Enter file numbers to delete (e.g. 1,3,4). Enter &quot;next&quot; for next group or &quot;exit&quot; to close program.\n&gt; &#039;)
        if answer.strip().lower() == &#039;next&#039;:
            break
        elif answer.strip().lower() == &#039;exit&#039;:
            sys.exit(0)
        try:
            numbers_to_del = set([int(item.strip()) for item in answer.split(&#039;,&#039;)])
        except:
            print(&#039;Error: wrong values!&#039;)
            continue
        if numbers_to_del &amp; set(range(1, len(val) + 1)) != numbers_to_del:
            print(&#039;Error: wrong values!&#039;)
            continue
        print(&#039;Delete these files?\n&#039;)
        files_to_del = [val[j -1] for j in numbers_to_del]
        for ftd in files_to_del:
            print(ftd)
        while True:
            answer2 = raw_input(&#039;\nEnter &quot;yes&quot; or &quot;no&quot;:\n&gt; &#039;)
            if answer2.lower() == &quot;yes&quot;:
                for ftd in files_to_del:
                    os.remove(ftd)
                break
            elif answer2.lower() == &quot;no&quot;:
                break
            else:
                print(&#039;Wrong answer!&#039;)
                continue
        
        break
    i += 1</code></pre></div><div class="codebox"><pre><code>$ ./dedup.py target/
Number of groups duplicate files: 2

Group 1 of 2:
    1 /mnt/sandbox/Python/files_dedup/target/folder3/fille3.txt
    2 /mnt/sandbox/Python/files_dedup/target/folder4/fille3.txt

Enter file numbers to delete (e.g. 1,3,4). Enter &quot;next&quot; for next group or &quot;exit&quot; to close program.
&gt; next

Group 2 of 2:
    1 /mnt/sandbox/Python/files_dedup/target/folder1/file1.txt
    2 /mnt/sandbox/Python/files_dedup/target/folder2/file1_copy.txt

Enter file numbers to delete (e.g. 1,3,4). Enter &quot;next&quot; for next group or &quot;exit&quot; to close program.
&gt; 2
Delete these files?

/mnt/sandbox/Python/files_dedup/target/folder2/file1_copy.txt

Enter &quot;yes&quot; or &quot;no&quot;:
&gt; yes</code></pre></div><p>ЗЫ. Если по-проще, то, наверное, приведёнными выше командами скинуть имена в файл и уже дальше с ним работать.</p>]]></content>
			<author>
				<name><![CDATA[-=Serj=-]]></name>
				<uri>https://linuxforum.ru/profile.php?id=16175</uri>
			</author>
			<updated>2013-10-16T11:54:09Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=370271#p370271</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=370167#p370167" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>drBatty пишет:</cite><blockquote><p>find это тоже такой &quot;скрипт&quot;</p></blockquote></div><div class="quotebox"><cite>-=Serj=- пишет:</cite><blockquote><p>А нафига мешать в кучу знание команд Linux и ЯП?</p></blockquote></div><p>а в чём разница?<br /></p><div class="quotebox"><cite>-=Serj=- пишет:</cite><blockquote><p>Какая команда? Я говорил про то, чтобы добавить в тот однострок фильтрацию по расширениям.</p></blockquote></div><p>добавьте, кто вам не даёт-то?</p>]]></content>
			<author>
				<name><![CDATA[drBatty]]></name>
				<uri>https://linuxforum.ru/profile.php?id=86</uri>
			</author>
			<updated>2013-10-16T06:58:25Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=370167#p370167</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=370140#p370140" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>drBatty пишет:</cite><blockquote><p>Если вы думаете, что изучать find не нужно, идите лучше в дворники. Хотя нет, лучше менеджером. Может получится с лозунгом &quot;питона хватит всем!&quot;.</p></blockquote></div><p>А нафига мешать в кучу знание команд Linux и ЯП?<br /></p><div class="quotebox"><cite>drBatty пишет:</cite><blockquote><p>мне эта команда даром не нужна.</p></blockquote></div><p>Какая команда? Я говорил про то, чтобы добавить в тот однострок фильтрацию по расширениям.</p>]]></content>
			<author>
				<name><![CDATA[-=Serj=-]]></name>
				<uri>https://linuxforum.ru/profile.php?id=16175</uri>
			</author>
			<updated>2013-10-16T05:39:58Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=370140#p370140</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=370135#p370135" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>Anatoly2012 пишет:</cite><blockquote><p>но мне проще было через скрипт... пока так понятнее</p></blockquote></div><p>find это тоже такой &quot;скрипт&quot; недоделанный. Но для поиска и обработки файлов лучше не бывает.</p><p>Если вы думаете, что изучать find не нужно, идите лучше в дворники. Хотя нет, лучше менеджером. Может получится с лозунгом &quot;питона хватит всем!&quot;. Ну у BG получилось же!&nbsp; <img src="https://linuxforum.ru/img/smilies/bm.gif" alt="bm" /> </p><div class="quotebox"><cite>-=Serj=- пишет:</cite><blockquote><p>Да не, просто на незавершенность</p></blockquote></div><p>мне эта команда даром не нужна.</p>]]></content>
			<author>
				<name><![CDATA[drBatty]]></name>
				<uri>https://linuxforum.ru/profile.php?id=86</uri>
			</author>
			<updated>2013-10-16T05:28:21Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=370135#p370135</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=370130#p370130" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>drBatty пишет:</cite><blockquote><p>намекаете на то, что питон умеет регулярки?</p></blockquote></div><p>Да не, просто на незавершенность <img src="https://linuxforum.ru/img/smilies/ab.gif" alt="ab" /></p>]]></content>
			<author>
				<name><![CDATA[-=Serj=-]]></name>
				<uri>https://linuxforum.ru/profile.php?id=16175</uri>
			</author>
			<updated>2013-10-16T05:08:56Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=370130#p370130</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=370110#p370110" />
			<content type="html"><![CDATA[<p><strong>drBatty</strong>, ваши аргументы не могу оспаривать, но мне проще было через скрипт... пока так понятнее <img src="https://linuxforum.ru/img/smilies/ab.gif" alt="ab" /></p>]]></content>
			<author>
				<name><![CDATA[Anatoly2012]]></name>
				<uri>https://linuxforum.ru/profile.php?id=26712</uri>
			</author>
			<updated>2013-10-16T01:39:27Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=370110#p370110</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=370109#p370109" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>-=Serj=- пишет:</cite><blockquote><p>Anatoly2012, какие требования?</p></blockquote></div><p>Чтобы скрипт показывал 2, 3... дубликата и выбор какой файл удалить.</p>]]></content>
			<author>
				<name><![CDATA[Anatoly2012]]></name>
				<uri>https://linuxforum.ru/profile.php?id=26712</uri>
			</author>
			<updated>2013-10-16T01:33:51Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=370109#p370109</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=369945#p369945" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>-=Serj=- пишет:</cite><blockquote><p>исключить некоторые расширения, типа - .gif&nbsp; .js .HLP .tif .TTF .css .ico .INF .ini .PFB</p></blockquote></div><p>намекаете на то, что питон умеет регулярки?</p><p>man find<br /></p><div class="quotebox"><blockquote><p>-regex pattern<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; File&nbsp; name matches regular expression pattern.&nbsp; This is a match on the whole<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; path, not a search.&nbsp; For example, to match a file named `./fubar3&#039;, you&nbsp; can<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; use the regular expression `.*bar.&#039; or `.*b.*3&#039;, but not `f.*r3&#039;.&nbsp; The regu-<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lar expressions understood by find are by default Emacs Regular Expressions,<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; but this can be changed with the -regextype option.</p></blockquote></div><div class="quotebox"><cite>Anatoly2012 пишет:</cite><blockquote><p>Да, но не исключает указанные выше расширения и не предоставляет выбора что и где удалить, а что оставить. В этом плане питон практичней.</p></blockquote></div><p>выбор нужен? И это есть у find</p><div class="quotebox"><blockquote><p>-ok command ;<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Like -exec but ask the user first.&nbsp; If the user&nbsp; agrees,&nbsp; run&nbsp; the&nbsp; command.<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Otherwise&nbsp; just&nbsp; return false.&nbsp; If the command is run, its standard input is<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; redirected from /dev/null.</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; The response to the prompt is matched against a pair of regular&nbsp; expressions<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; to&nbsp; determine&nbsp; if&nbsp; it&nbsp; is an affirmative or negative response.&nbsp; This regular<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; expression is obtained from the system if the `POSIXLY_CORRECT&#039;&nbsp; environment<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; variable is set, or otherwise from find&#039;s message translations.&nbsp; If the sys-<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tem has no suitable definition, find&#039;s own definition&nbsp; will&nbsp; be&nbsp; used.&nbsp; &nbsp; In<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; either&nbsp; case,&nbsp; the&nbsp; interpretation&nbsp; of the regular expression itself will be<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; affected by the environment variables&nbsp; &#039;LC_CTYPE&#039;&nbsp; (character&nbsp; classes)&nbsp; and<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &#039;LC_COLLATE&#039; (character ranges and equivalence classes).</p></blockquote></div><p>и вообще, дрова лучше пилить бензопилой. Да, я знаю, ваш швейцарский нож тоже с пилой в комплекте. Но моя бензопила практичнее.<br /></p><div class="quotebox"><cite>Anatoly2012 пишет:</cite><blockquote><p>Не надо выкидывать то, что реально помогает и нет пока лучшей альтернативы.</p></blockquote></div><p>ой, а мужики-то не знали... А как вы думаете, что делали тогда, когда вашего питона не было?<br /></p><div class="quotebox"><cite>Anatoly2012 пишет:</cite><blockquote><p>Простите, а как правильно будет связать эти команды:</p></blockquote></div><p>по умолчанию find связывает по &quot;И&quot;</p><div class="codebox"><pre><code>find УСЛОВИЕ1 AND УСЛОВИЕ2 AND УСЛОВИЕ3 AND ДЕЙСТВИЕ</code></pre></div><p>ДЕЙСТВИЕ выполнится тогда, и только тогда, когда все условия истинны. Самое ДЕЙСТВИЕ -- тоже условие, ибо всякая команда выдаёт код возврата, и она истинна, если код равен 0.</p>]]></content>
			<author>
				<name><![CDATA[drBatty]]></name>
				<uri>https://linuxforum.ru/profile.php?id=86</uri>
			</author>
			<updated>2013-10-15T06:52:34Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=369945#p369945</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=369938#p369938" />
			<content type="html"><![CDATA[<p><strong>Anatoly2012</strong>, какие требования?</p>]]></content>
			<author>
				<name><![CDATA[-=Serj=-]]></name>
				<uri>https://linuxforum.ru/profile.php?id=16175</uri>
			</author>
			<updated>2013-10-15T04:30:42Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=369938#p369938</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=369929#p369929" />
			<content type="html"><![CDATA[<p><strong>-=Serj=-</strong>, а скрипт допилить никак не получится?</p>]]></content>
			<author>
				<name><![CDATA[Anatoly2012]]></name>
				<uri>https://linuxforum.ru/profile.php?id=26712</uri>
			</author>
			<updated>2013-10-14T21:51:48Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=369929#p369929</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: Дубликаты]]></title>
			<link rel="alternate" href="https://linuxforum.ru/viewtopic.php?pid=369740#p369740" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>Lupo Alberto пишет:</cite><blockquote><p>P.S. <a href="http://ru.clihelper.com/find/">http://ru.clihelper.com/find/</a><br />P.S.S. man find</p></blockquote></div><p>Это читал уже, но мне еще не хватает знания основ работы с командами в консоли, а главное времени. По-тихоньку может научимся...</p>]]></content>
			<author>
				<name><![CDATA[Anatoly2012]]></name>
				<uri>https://linuxforum.ru/profile.php?id=26712</uri>
			</author>
			<updated>2013-10-13T15:21:25Z</updated>
			<id>https://linuxforum.ru/viewtopic.php?pid=369740#p369740</id>
		</entry>
</feed>
