1
votes

I have the following command that I run to lowercase files/directories, replace . with _ and various other manipulations. The problem with it is that it seems to try to rename the directories first and then it cannot find the files below it. Is there a way to rename all files in a directory first then the directory itself recursively? e.g.

  • directory1
    • file1
    • file2
    • directory1
      • file1
      • file2
    • directory2
      • file1
  • directory2
    • file1
    • file2

My code is

while IFS= read -rd '' entry; do
   entry="${entry#./}"         # strip ./
   if [[ -d $entry ]]; then
      rename  'y/A-Z/a-z/; s/ /_/g; s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   else
      rename  'y/A-Z/a-z/; s/\.(?=.*\.)/_/g; s/ /_/g;  s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   fi
done < <(find . -iname '*' -print0)
3
You need to use recursion to achieve that in one shot or rename files only first then the directoriesdganesh2002
I'd use find to create a list and sort that bottom up regarding directory/file depth.yacc

3 Answers

0
votes

Here is sample UNTESTED code using recursion :

recurse()
{
for entry in "$1"/*; do
   entry="${entry#./}"         # strip ./
   if [[ -d $entry ]]; then
      recurse $entry
      rename  'y/A-Z/a-z/; s/ /_/g; s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   else
      rename  'y/A-Z/a-z/; s/\.(?=.*\.)/_/g; s/ /_/g;  s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   fi
done
}

recurse "/home"
0
votes

Have you looked at this answer? Your scenario is more complicated but it looks like they were dealing with the same difficulty in terms of recursion.

0
votes

I was thinking of something along this line:

find /path |awk -F/ '{print NF,$0}' |sort -r -n -k 1 |cut -f2- -d' ' |\
  while IFS= read -rd '' entry; do
    # ...
  done

The idea is to prepend each line with the number of / and sort reversely according to this field:

4 /path/dir1/file1
4 /path/dir2/file2
3 /path/dir1
3 /path/dir2
2 /path

Then cut away the first column. This way you can work on the entries bottom up to avoid renaming issues.