Bash脚本删除另一个文件夹中的文件(如果

时间:2016-11-08 06:09:44

标签: bash

该脚本的目标是检查文件夹中是否存在文件名。如果文件名不存在,则删除该文件。

这是我到目前为止的脚本

#!/bin/bash
echo "What's the folder name?"
read folderName
$fileLocation="/home/daniel/Dropbox/Code/Python/FR/alignedImages/$folderName"

for files in "/home/daniel/Dropbox/Code/Python/FR/trainingImages/$folderName"/*
do
  fileNameWithFormatFiles=${files##*$folderName/}
  fileNameFiles=${fileNameWithFormat%%.png*}
  for entry in "/home/daniel/Dropbox/Code/Python/FR/alignedImages/$folderName"/*
  do
    fileNameWithFormat=${entry##*$folderName/}
    fileName=${fileNameWithFormat%%.png*}
    if [ -f "/home/daniel/Dropbox/Code/Python/FR/alignedImages/$fileNameFiles.jpg" ]
    then
      echo "Found File"
    else
      echo $files
      rm -f $files
    fi
  done
done
read

我有两个文件夹,alignedImagestrainingImages

alignedImages中的所有图片都在trainingImages内,但不在其他地方。所以,我试图做到这一点,以便如果trainingImages不包含与alignedImages中的文件同名的文件,那么我希望它删除{{1中的文件}}

此外,图片不一样,所以我不能只比较md5或哈希或其他什么。只是文件名是相同的,除了它们是.jpg而不是.png

2 个答案:

答案 0 :(得分:1)

fileLocation="/home/daniel/Dropbox/Code/Python/FR/alignedImages/$folderName"
echo "What's the folder name?"
read folderName

 rsync --delete --ignore-existing $fileLocation $folderName

rsync命令是您正在查找的内容,当给出--delete选项时,它将从目标目录中删除源目录中不存在的任何文件,--ignore-existing将导致rsync如果目标目录中已存在具有相同名称的文件,则跳过从源复制文件。

这样做的副作用是它会复制源目录中的任何文件,但不会复制到目标文件中。你说源中的所有文件都在目的地,所以我猜这没关系

答案 1 :(得分:0)

有更好的方法!文件,而不是for循环!

#!/bin/bash
echo "What's the folder name?"
read folderName

cd "/home/daniel/Dropbox/Code/Python/FR/alignedImages/$folderName"
find . -type f -name "*.png" | sed 's/\.png//' > /tmp/align.list

cd "/home/daniel/Dropbox/Code/Python/FR/trainingImages/$folderName"
find . -type f -name "*.jpg" | sed 's/\.jpg//' > /tmp/train.list

这里是如何查找两个列表中的文件:

fgrep -f /tmp/align.list /tmp/train.list | sed 's/.*/&.jpg/' > /tmp/train_and_align.list

fgrep -v找到非匹配而非匹配:在列车中查找文件但未对齐:

fgrep -v -f /tmp/align.list /tmp/train.list | sed 's/.*/&.jpg/' > /tmp/train_not_align.list

测试删除train_not_align.list中的所有文件:

cd "/home/daniel/Dropbox/Code/Python/FR/trainingImages/$folderName"
cat /tmp/train_not_align.list | tr '\n' '\0' | xargs -0 echo rm -f

(如果这会产生良好的输出,请删除echo语句以实际删除这些文件。)

相关问题