I have several folders in the following structure that I would like to sort.

For example:


These are nested folders with nothing in them except for the next folder.

I want to cut the path to this


I do not want to move the folders to the root level folder but to just below their parent folder.

The best command I can think to run is this:

mv sub*/aaaa/bbbb/cccc/dddd

However this would bring everything to the root level.

Or I could run the command inside each sub folder however this would still be tedious.

mv aaaa/bbbb/cccc/dddd

2 Answers 2


Since the files need to end up in different directories, you need to run mv multiple times, at least once per destination directory. You can do this by running mv in a for loop.

for x in /root/*
  mv -i "$x"/*/*/*/* "$x"

The loop body (the mv command) is executed for each entry in the /root directory in turn. At each run of the loop body, "$x" is replaced by the path /root/subN. The command mv -i "$x"/*/*/*/* "$x" moves a file like /root/sub1/aaaa/bbbb/cccc/dddd to the directory /root/sub1, i.e. the file is moved to /root/sub1/dddd.

With the option -i, mv will ask if the destination file already exists, which could happen if you have e.g. both /root/sub1/aaa1/bbb/ccc/ddd and /root/sub1/aaa2/bbb/ccc/ddd.

find /root -maxdepth 6 -mindepth 6 -type d | awk -F \/ '{ print "mv "$0" "$1"/"$2"/"$3"/"$6 }' | sh

Use the find command with particular emphasis on the max and minimum directory depths, then take the listing and parse through awk to build a mv command we can execute with sh. Remove the "| sh" to test before adding to execute.

  • Building a shell command in this way is a very bad idea. It's dangerous. The awk command prints file names, but sh reads them as shell code. If there's any shell special character in one of the file names, it'll be executed as code. Don't do that. Make awk run the command instead, but be careful about quoting the file names properly. Awk is not the easiest tool to use here. Aug 8, 2017 at 23:47
  • Fair point but every command has an element of risk and it is up to the system administrator to assess the risk and look at options accordingly. Aug 9, 2017 at 8:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.