簡體   English   中英

如何查找所有不具有名稱相同但擴展名不同的匹配文件的文件

[英]how to find all files that dont have a matching file with the same name but different extension

我有一個超過一百萬個文件的文件夾。 文件成對出現,只是擴展名不同(例如a1.ext1 a1.ext2,a2.ext1,a2.ext2 ...)

我需要掃描此文件夾,並確保它滿足此要求(文件耦合),並且如果我找到一個不匹配的文件,則應將其刪除。

我已經在python中完成了此操作,但是在處理7位數字的文件時速度非常慢。

有沒有辦法使用Shell命令/腳本來做到這一點?

在另一個答案的基礎上,您可以使用類似以下的腳本(它應該位於文件所在的目錄中,並應在該目錄中執行):

#!/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變量來配置將沒有配對的文件移到THRASH

在具有3.0 GHz和2 GB RAM的雙核Pentium上 ,一次運行耗時63.7秒(10000對,文件夾中缺少1500對)。

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

這應該顯示擴展名多於或少於兩個的文件名。

試試這個:

#!/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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM