【问题标题】:Deleting files with same using shell script使用shell脚本删除相同的文件
【发布时间】:2011-11-24 23:34:49
【问题描述】:

我完全是 shell 脚本的新手。 我需要比较两个目录中的文件名并删除同名文件。

EG:

Directory1/
one
two
three
four

Directory2/
two
four
five

运行脚本后,目录将是:

Directory1/
one
three

Diretory2/
five

谢谢

【问题讨论】:

  • 我试过 diff Directory1/ Directory2/ 但它显示的是每个目录中的单个文件,而不是重复文件。
  • 你只需要删除同名文件?不同的文件可以具有相同的名称。正确的方法是使用cksummd5 来识别文件是否确实重复。
  • 只要同名就好了。就我而言,内容并不重要。谢谢。

标签: bash shell


【解决方案1】:

test -f 测试文件是否存在:

cd dir1
for file in *
do
    test -f ../dir2/$file && rm $file ../dir2/$file
done
cd ..

【讨论】:

    【解决方案2】:

    又快又脏:

    while read fname
    do 
        rm -vf Directory{1,2}/"$fname"
    done < <(sort 
                  <(cd Directory1/ && ls) 
                  <(cd Directory2/ && ls) | 
             uniq -d)
    

    这假设了一些关于文件名的事情,但它应该可以通过显示的输入和类似情况让您到达那里。

    现在也测试了:

    mkdir /tmp/stacko && cd /tmp/stacko
    mkdir Directory{1,2}
    touch Directory1/{one,two,three,four} Directory2/{two,four,five}
    

    运行命令显示:

    removed `Directory1/four'
    removed `Directory2/four'
    removed `Directory1/two'
    removed `Directory2/two'
    

    结果树是:

    Directory1/one
    Directory1/three
    
    Directory2/five
    

    【讨论】:

    • 为什么使用双倍小于
    • &lt; 表示输入重定向,&lt;(cmd) 表示进程替换(打开命令的输出像文件(描述符));因此&lt; &lt;(cmd) 将输入从代表cmd 输出的伪文件(管道)重定向。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    • 2016-08-17
    相关资源
    最近更新 更多