1

I have a directory with 6 subdirectories. Each subdirectory also have a variable number of subdirectories. These last directories have variable numbers of *.jpg files. The jpg files are named in the form 0000.jpg, 0001.jpg and so on.

I am interested in getting the last 100 *.jpg files ( all directories have > 100 files), and storing them in separate directories with similar structure as the original directories.

What is the best way of doing it?

Zanna
  • 70,465
H.H
  • 11

1 Answers1

0

In the parent with the 6 subdirectories:

mkdir ../newdirs

Then:

for d in */*; do mkdir -p ../newdirs/"$d"; i=0; j=$(stat "$d"/* --printf "%i\n" | wc -l); for f in "$d"/*; do [[ -f "$f" ]] && (( (j - ++i) < 100 )) && echo mv -v -- "$f" ../newdirs/"$d"; done; done

Remove echo after testing to actually move the files.
More readably:

for d in */*; do 
  mkdir -p ../newdirs/"$d" 
  i=0
  j=$(stat "$d"/* --printf "%i\n" | wc -l)
  for f in "$d"/*; do 
    [[ -f "$f" ]] && 
    (( (j - ++i) < 100 )) && 
      echo mv -v -- "$f" ../newdirs/"$d"
  done
done

Notes

  • mkdir ../newdirs make a new directory for the moved files at the same level as the current one (ie in the parent .. of both)
  • for d in */*; do for each sub-sub directory...
  • mkdir -p ../newdirs/"$d" make a directory in the parallel structure, using -p to create parent directories as needed and
  • i=0 set a variable to 0 for counting iterations
  • j=$(stat "$d"/* --printf "%i\n" | wc -l) count the files in the sub-subdirectory and assign this number to j
  • for f in "$d"/*; do for all the contents of the sub-subdirectories
  • [[ -f "$f" ]] && if it's a file
  • (( (j - ++i) < 100 )) && and if the number of files in the directory minus the number of times the loop has been run is less than 100, then...
  • mv -v -- "$f" ../newdirs/"$d" move the file to the corresponding directory in the new structure.

for iterates over files in an ordered way, so this method will give the last 100 files as listed numerically.

You can adjust ../newdirs to the path you want.

Zanna
  • 70,465