0

I have list of sub folders inside a parent folder as follow:

Parent folder
    folder1
       foldera
    folder2
       folderb
    folder3
       folderc

I want to rename the subfolders only in the second level by removing the last two charcters in the subfolder name how can I do this? I tried something like

find . -depth -type d -exec sh -c 'mv "${0}" "${0%??}"' {} \; 

but it didn't work.

2 Answers 2

0

No need for find, it works with pure bash, considering the following directory structure:

./folder3
./folder3/folderc
./folder2
./folder2/folderb
./folder1
./folder1/foldera

The command:

for f in folder*/*/; do mv -v "$f" "${f%???}"; done

After:

./folder3
./folder3/folde
./folder2
./folder2/folde
./folder1
./folder1/folde

The filename expansion matches here only folders within the subfolder; folder*/*/, that's why there is a slash at the end. The mv command remove the last two characters, in the case above it's 3 characters because the ending slash also counts in the variable value.

2
  • Thanks! Kindly why you used echo before mv?
    – user88036
    Aug 4, 2015 at 20:22
  • @MJA Thats a mistake, sry. I echoed the command before I tested it and I copied the wrong one, I correted it.
    – chaos
    Aug 4, 2015 at 20:28
0

The trick is to use the mindepth and maxdepth argument Here is the command that I used:

`find folder -mindepth 2 -maxdepth 2 -type d -exec sh -c 'mv "${0}" "${0%?}"' {} \;`

Also note that I used ${0$?} instead of the double ?? that you used. One way to debug find problems like these is to apend your action with echo. So in the above example you would place an echo before the mv command.

$ find .
.
./folder
./folder/folder1
./folder/folder1/foldera
./folder/folder2
./folder/folder2/folderb
./folder/folder3
./folder/folder3/folderc
$ find folder -mindepth 2 -maxdepth 2 -type d -exec sh -c 'mv "${0}" "${0%?}"' {} \;
$ find .
.
./folder
./folder/folder1
./folder/folder1/folder
./folder/folder2
./folder/folder2/folder
./folder/folder3
./folder/folder3/folder

Incidentally, I could have used find . or find folder since I was in the parent directory of folder. However, if you use find . for your exec command, then every subdirectory in the parent directory would have been converted. It is usually better to explicitly list out the directory when you are doing moves, deletes, etc to avoid unexpected results.

2
  • Thanks! Kindly one more question. how can this command find sub folders of different names not only the ones named "folder". ?
    – user88036
    Aug 4, 2015 at 17:28
  • The command finds any directory at the specified level regardless of the name. When I specified "find folder ..." that was just the starting directory. Aug 4, 2015 at 18:35

You must log in to answer this question.