Home > Software engineering >  How to iterate through folders and subfolders to delete n number of files randomly?
How to iterate through folders and subfolders to delete n number of files randomly?

Time:08-11

I have 4 folders (named W1, W3, W5, W7) and each one of those folders has approximately 30 subfolders (named M1 - M30). Each subfolder contains 24 .tif files (named Image_XX.tif).

I need to randomly "sample" each subfolder, more specifically, I need to get rid of 14 .tif files while keeping 10 .tif files in each subfolder.

I figure that deleting 14 files at random is easier than choosing 10 files at random and copying them to new subfolders within folders.

I thought that writing a bash script to do so would be the way, but I'm fairly new to programming and I'm stuck.

Below is one of the several scripts I've tried:

#!/bin/bash

for dir in /Users/Fer/Subsets/W1/; do
    if [ -d "$dir" ]; then
        cd "$dir"
        gshuf -zn14 -e *.tif | xargs -0 rm
        cd ..
    fi
done

It runs for a second, but nothing seems to happen. Any help is appreciated.

CodePudding user response:

  1. For every subdirectory.
    1. Find all files.
    2. Choose a random number of files from the list.
    3. Delete.

I think something along:

for dir in /Users/Fer/Subsets/W*/M*/; do
    printf "%s\n" "$dir"/*.tif |
    shuf -z -n 14 |
    xargs -0 -t echo rm -v
done

CodePudding user response:

Used some of the suggestions above and the code below worked:

for dir in /Users/Fer/Subsets/W*/M*; do
    gshuf -zn14 -e "$dir"/*.tif | xargs -0 rm
done
  • Related