如何查找没有相同名称但扩展名不同的匹配文件的所有文件

时间:2013-03-28 15:26:02

标签: linux system-calls

我有一个包含超过100万个文件的文件夹。 文件来自夫妻,只有他们的扩展名不同(例如a1.ext1 a1.ext2,a2.ext1,a2.ext2 ......)

我需要扫描此文件夹并确保它满足此要求(文件耦合),如果我找到没有匹配的文件,我应该删除它。

我已经在python中完成了它,但是当使用7位数的文件时它非常慢..

有没有办法使用shell命令/脚本执行此操作?

3 个答案:

答案 0 :(得分:1)

基于另一个答案,您可以使用这样的脚本(它应该位于文件所在的同一目录中,并且应该在那里执行):

#!/usr/bin/env bash 
THRASH=../THRASH
mkdir "$THRASH" 2> /dev/null

for name in $(ls *.{ext1,ext2} | cut -d. -f1 | sort -u); do
    if [ $(ls "$name".{ext1,ext2} 2> /dev/null | wc -w) -lt 2 ]; then
        mv "$name".{ext1,ext2} "$THRASH" 2> /dev/null
    fi;
done

您可以通过修改THRASH变量来配置移动没有配对的文件的位置。

在具有3.0 GHz和2 GB RAM的双核 Pentium 上,一次运行需要63.7秒(10000对,文件夹中缺少每对成员约1500个)。

答案 1 :(得分:0)

Python应该更快;但是如果你想尝试bash:

for file in $(ls | cut -d. -f1 | sort -u); do
    if [ $(ls $file.* | wc -l) -ne 2 ]; then
        echo "too much extension for $file"
    fi
done

这应该显示多于或少于两个扩展名的文件名。

答案 2 :(得分:0)

试试这个:

#!/bin/bash

for file in *.ext1 *.ext2
do
  #name is the substring before the '.'
  name=${file%.*}
  #ext is the substring after the '.'
  ext=${file#*.}
  case $ext in
    "ext1")
      sibling="$name.ext2";
      #does it haves a sibling?
      #if it does not,remove the file
      ls | grep $sibling >/dev/null;
      if [ $? -ne 0 ]
      then
        rm $file
      fi;;
    "ext2")
      sibling="$name.ext1";
      #does it haves a sibling?
      #if it does not,remove the file
      ls | grep $sibling >/dev/null;
      if [ $? -ne 0 ]
      then
        rm $file
      fi;;
  esac      
done
相关问题