How to delete files by names of files NOT in another directory

2 months ago by WastedJobe to c/linuxquestions

Hi, I want to delete .cr2 files that don't have a .jpg file in another directory. The idea is:
-Search files in jpg directory
-Select files in .cr2 directory that dont have matching names
-Delete them while keeping the .cr2s that have a corresponding .jpg so I have raw files for the good photos
Is this possible in a single command or do I have to write a script to do this?

ignotum 5 points 2 months ago

Everything can be done as a single (but often quite long) command, something like this:

for filepath in A/*; do filename=$(basename "$filepath"); name="${filename%.*}; match=$(ls B/"$name".* 2>/dev/null); [ -z "$match" ] && rm "$filepath"; done

What it does is

  1. Loops over the files in directory A
  2. Gets the filename (my_file.ext)
  3. Strips the extension
  4. Looks for any files in B with the same name but any extension
  5. If no match, delete the file (from A)
    I haven't tested it so might be some typos in there, also maybe replace rm with echo and run it first just to see what files it would have deleted, there's no undo when you use rm

Also if there are 100k+ files this is likely going to be relatively slow, then i would create two files containing the names of all the files in each directory, sort them, then there is a command to find differences between them very efficiently but i don't remember which...

path: 0 25164450, hotness: undefined, score: 5, children: 0
cadekat 2 points 2 months ago

I believe comm is your friend here. Something like get the contents of both directories, strip the suffix, sort, pass both lists to comm, re-add the extension, and delete those files.

path: 0 25169950, hotness: undefined, score: 2, children: 0
orsam 1 point 2 months ago

Does one of the diff options in this discussion help to generate the list of files? I'm limited to a phone for a few days, but I can test them later.

path: 0 25259113, hotness: undefined, score: 1, children: 0
linuxquestions
linuxquestions

@lemmy.zip

login for more options
4272
313
210

Linux questions Rules (in addition of the Lemmy.zip rules)

  • stay on topic
  • be nice (no name calling)
  • do not post long blocks of text such as logs
  • do not delete your posts
  • only post questions (no information posts)

Tips for giving and receiving help

  • be as clear and specific
  • say thank you if a solution works
  • verify your solutions before posting them as facts.

Any rule violations will result in disciplinary actions

go to feed...