0

I have a very large directory of files, each with it'd own subdirectory. In those subdirectories are videos of various qualities (1080p, 720p... etc). I only want to keep the video of the highest quality (therefore the largest size). Is there a way to do this via command-line or batch file?

Parent_directory

- Video_A
-- Video_A_1080p
--video_A_720p

-Video_B
-- Video_B_1080p
--video_B_720p
-- Video_B_480p

Note that the name of the videos do not necessarily have the resolutions in the file name. I'm just illustrating the directory structure.

The result should be:

Parent_directory

- Video_A
-- Video_A_1080p

-Video_B
-- Video_B_1080p
0

Something like:

for dir in *
do
  cd $dir
  echo rm $(ls -1S | tail -n +2)
  cd ..
done

Remove echo to make it work for real. Test it before (never do things like that before checking you have a valid full backup)! It has various edge cases: it assumes there are only directories on top, not files, and that files in directory are "properly" named, that is without spaces. And that you do not have millions of files either, otherwise the command line will overflow.

ls -1S gives a list of all files sorted on size. The tail -n +2 keeps only everything from the second line to the end in the list, that is it removes the first line, which is the biggest file. The rest is fed to rm for deletion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.