Rename directories based on number of files within in Linux

bash, linux, regex, rename

Solution

before

.
├── d1
│   ├── f1
│   ├── f2
│   └── f3
├── d2
│   ├── f4
│   └── f5
└── d3
    ├── d4
    │   └── f9
    ├── f6
    ├── f7
    └── f8

run the command at top level 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

after

.
├── 2-d2
│   ├── f4
│   └── f5
├── 3-d1
│   ├── f1
│   ├── f2
│   └── f3
└── 4-d3
    ├── d4
    │   └── f9
    ├── f6
    ├── f7
    └── f8

Problem

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 within. The format isn't super important as long as it's not too long. I want to be able to run this script as a cron every hour or so to update the 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, maybe a few more files will have been added and removed, 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 so far, but I can't figure out how to do the regex replacement on the filename ``` #!/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 ```

Original source