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.

2
  • 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: unix.stackexchange.com/questions/29214/… It will furthermore add credibility if you actually showed what you have attempted. Commented May 1, 2017 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
    Commented May 1, 2017 at 16:32

2 Answers 2

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
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.

5
  • xargs takes a blank or newline separated list on input when quotes and backslashes can be used to escape those separators and each other. Commented May 1, 2017 at 12:44
  • @StéphaneChazelas Yeah, forgot about xargs.
    – phk
    Commented May 1, 2017 at 12:44
  • Yes, xargs is pretty much useless without GNU's -r0 extensions (and then you'd need GNU awk -v 'RS=\0' -v 'ORS=\0'). Commented May 1, 2017 at 12:45
  • @StéphaneChazelas Shouldn't -d '\n' be suffice in the real world?
    – phk
    Commented May 1, 2017 at 12:46
  • That's better but that still doesn't solve the problem with newline characters. It's also a lot less portable than -0 Commented May 1, 2017 at 12:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .