Score:2

how to recursively remove files from one folder if its file name doesn't appear in another folder

in flag

I have two folders where one contains txt files and the other .jpg files with the exact name. However, txt files are much more than jpg files.

folder_1/00.txt
folder_1/01.txt 
folder_1/02.txt 
folder_1/03.txt 
folder_1/04.txt   

folder_2/00.jpg
folder_2/01.jpg 
folder_2/02.jpg 

Here, I need to remove 03.txt and 04.txt because these names don't appear in folder_2

Score:3
cn flag

Here's one way:

$ for file in folder_1/*.jpg; do 
    fileName="${file##*/}"
    [[ -e folder_2/${fileName/.txt/.jpg} ]] || echo rm -- "$file"
done
rm -- folder_1/03.txt
rm -- folder_1/04.txt

The for loop iterates over all non-hidden files and directories in folder_1 whose name ends in .jpg, saving each as $file. Next, fileName="${file##*/}" sets the variable $fileName to the value of $file with everything until the last / removed, which means it will be the file's name without the directory. Finally, with [[ -e folder_2/${fileName/.txt/.jpg} ]] || echo rm -- $file, we check if there is a file in folder_2 with the same name but a .txt extension and, if not, echo rm -- "$file". If this does what you want, remove the echo and run again to actually delete the files:

for file in folder_1/*.jpg; do 
    fileName="${file##*/}"
    [[ -e folder_2/${fileName/.txt/.jpg} ]] || rm -- "$file"
done

The -- in rm -- "$file" isn't necessary here but is a good habit to have: it ensures that anything after the -- is not parsed as an option to rm, therefore allowing the command to also work on file names starting with an -.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.