Ubuntu – How to compare list of files with different extensions and delete extra files

bashcommand line

I have 2 folders one contains images files and the second contains text files each text file have the same name as the image file and contains information about the image.eg:

   -Labels:
     -1.txt
     -2.txt
     -3.txt
     -6.txt
   -Images:
     -1.jpg
     -2.jpg
     -3.jpg
     -4.jpg
     -5.jpg
     -6.jpg

I want to delete images who has not a text file(in this example:4.jpg,5.jpg), I found a method how to determinate the different files but I can't delete them.

diff <(ls -1 ./Images | sed s/.jpg//g) <( ls -1 ./Labels | sed s/.txt//g)

Best Answer

Here is a small bash script that can help you to solve this task:

#!/bin/bash
for file in Images/*.jpg
do
    if [[ ! -f "Labels/$(basename ${file%.*}).txt" ]]
    then
        echo rm "$file"
    fi
done
  • Remove echo to do the actual changes.

The script must be executed in the parent directory, here it is formatted as inline command:

for f in Images/*.jpg; do if [[ ! -f "Labels/$(basename ${f%.*}).txt" ]]; then echo rm "$f"; fi; done
Related Question