Renaming directories based on the number of files inside Linux

I have the following layout:

  • d1
    • f1
    • f2
    • f3
  • d2
    • f4
    • f5
  • d3
    • f6
    • f7
    • f8
    • d4
      • f9

What I want to do is rename the root directories to contain the number of (recursive) files contained inside. The format is not very important if it is not too long. I want to be able to run this script as cron every hour or so to update directory names, so after the first run it will look like this:

  • 3-d1
    • f1
    • f2
    • f3
  • 2-d2
    • f4
    • f5
  • 4-d3
    • f6
    • f7
    • f8
    • d4
      • f9

Then, after the second run, perhaps a few more files will be added and deleted, and now it looks like this:

  • 1-d1
    • f1
  • 4-d2
    • f2
    • f3
    • f4
    • f5
  • 10-d3
    • f6
    • f7
    • f8
    • d4
      • f9
      • f10
      • f11
      • f12
      • f13
      • f14
      • f15

I have the following bash script, but I can’t figure out how to replace regular expressions with a file name

#!/bin/bash

TARGETPATH=/home/pritchea/test
for CURDIR in `ls -l $TARGETPATH`
do
  if [ -d $TARGETPATH/$CURDIR ]; then
    echo "$CURDIR is a directory"
    FILECOUNT=`find $TARGETPATH/$CURDIR -type f | wc -l`
    echo " and there are $FILECOUNT file(s)";
  fi
done
+5
2

.
β”œβ”€β”€ d1
β”‚   β”œβ”€β”€ f1
β”‚   β”œβ”€β”€ f2
β”‚   └── f3
β”œβ”€β”€ d2
β”‚   β”œβ”€β”€ f4
β”‚   └── f5
└── d3
    β”œβ”€β”€ d4
    β”‚   └── f9
    β”œβ”€β”€ f6
    β”œβ”€β”€ f7
    └── f8

dir

cd /home/pritchea/test

for i in *
do
    [[ -d $i ]] || continue
    n=${i#*-}
    c=$(find "$i" -type f -printf x | wc -c)
    [[ $i == $c-$n ]] && continue
    mv -f "$i" "$c-$n"
done

.
β”œβ”€β”€ 2-d2
β”‚   β”œβ”€β”€ f4
β”‚   └── f5
β”œβ”€β”€ 3-d1
β”‚   β”œβ”€β”€ f1
β”‚   β”œβ”€β”€ f2
β”‚   └── f3
└── 4-d3
    β”œβ”€β”€ d4
    β”‚   └── f9
    β”œβ”€β”€ f6
    β”œβ”€β”€ f7
    └── f8
+3

. $TARGETPATH, ls -l, , , , $CURDIR. : (find -f , ..).

wc -l , [ 1], [1], sed.

, , , : 2-3-dir, , newdirname CURDIR; , , mv.


#!/bin/bash

TARGETPATH=.
for CURDIR in `ls -l $TARGETPATH`
do
  if [ -d $TARGETPATH/$CURDIR ]; then
    echo "$CURDIR is a directory"
    #Also strip whitespace from FILECOUNT
    FILECOUNT=$(ls -l $CURDIR | grep ^- | wc -l | sed -e 's/[ \t]*//')
    echo " and there are $FILECOUNT file(s)";

    # We should remove the number from the directory.
    newdirname="$FILECOUNT"-"$(echo "$CURDIR" | sed -e 's/^[0-9]*-//')"
    echo " New directory name: ["$newdirname"]"
    # Now we move the old-dir to the new-dir. 
    if [[ "$CURDIR" != "$newdirname" ]]; then
    mv $TARGETPATH/$CURDIR $TARGETPATH/$newdirname
    fi  
  fi  
done
0

All Articles