I'm running Red Hat Release 6.5 (Santiago). The problem I'm facing is that I have a bunch of files in the following directory structure:

├── ABC
│   └── temp2
│       └── temp2.txt
└── DEF
    └── temp2
        └── temp2.txt

I'm trying to change it to the structure as below, but have no idea how to get it done.

├── ABC.txt
└── DEF.txt

Any help would be greatly appreciated!

2 Answers 2


You need to create a small script file to do your rename/move: call it rnmv, say, and put the following command into it:

f="${1#./}"; echo mv "$f" "${f%%/*}.${f##*.}"

Don't forget to chmod +x rnmv. Then go to the root directory and call rnmv from a find command:

cd {wherever temp2 root is}
find . -name "temp2.txt" -exec rnmv "{}" \;

When you are happy that the correct mv commands are being created, remove the echo from rnmv and your rename/move will be done.

One final task is to remove the empty subdirectories:

find . -name temp2 -exec rmdir "{}" \;

This is safe, as rmdir will not remove a directory with files in it. Depending on the order of finding the directories, you may need to repeat the command for structures like ABC/temp2/temp2, as the temp2 will not be empty until the second is deleted.

Note that if ABC, say, has more that one temp2.txt file in its subdirectories, each mv command will overwrite the previous ABC.txt, and only the last found will be left afterwards.

  • Hi, the right commands seem to get echoed, but the files don't seem to be moved for some reason. Oct 2, 2014 at 16:40
  • You need to delete echo in front of mv in the script file: sorry if this was less than clear.
    – AFH
    Oct 2, 2014 at 18:24
  • Aagh. I seem to have read past that without realizing it. It worked. Thanks! Oct 3, 2014 at 2:44
mv /temp2/ABC/temp2/temp2.txt /temp2/ABC.txt
mv /temp2/DEF/temp2/temp2.txt /temp2/DEF.txt

Depending on where the high-level temp2 directory is - I cannot tell from your example.

  • Sorry I wasn't more clear. I have the same structure for hundreds of files; I'm looking for some sort of script. Oct 2, 2014 at 16:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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