0

I'm trying to do something that looks pretty simple but I haven't been able to solve.

I have a directory with a bunch of subdirectories all of them with multiple files (jpg files). I want to execute a command which keep only 4 or N files inside of these directories. The order of the files isn't important as I have seen related questions depending on the time they were created

I have played with ls + head and trying to put find in a loop with the -delete option but still no luck.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Biruwon
  • 103
  • Schoolwork? If not - then please clarify what you need and why. Just keeping 4 random files seems strange. If the order is not important - then all answers using date would be usable. Or something like this: https://unix.stackexchange.com/questions/29214/copy-first-n-files-in-a-different-directory It will furthermore add credibility if you actually showed what you have attempted. – Claus Andersen May 01 '17 at 12:01
  • why I need to add an explanation or purpose if that's not needed to understand the question? Anyway, just for you, I have a bunch of folders full of images which I got from a scraper but I only need to keep 4 of them for my application – Biruwon May 01 '17 at 16:32

2 Answers2

2

Maybe something like:

for dir in /target/dir/*/; do
  (cd -- "$dir" && set -- *.jpg && [ "$#" -gt 4 ] && shift 4 && rm -f -- "$@")
done

Which with zsh, you could shorten to:

for dir (/target/dir/*(/)) rm -f $dir/*.jpg(N[5,-1])
0

Assuming those are regular files with no blanks, newlines, quotes, backslashes or invalid characters in their paths:

find /target/dir/ -type f \
  | awk '{t=$0; gsub(/\/[^/]*$/, "", t); if(a[t]++ < 4) print}' \
  | xargs rm --

See the comments below for how you could possibly adapt it for more funny file names if your utilities support certain extensions.

phk
  • 5,953
  • 7
  • 42
  • 71