Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have bunch of directories containing the file with the same name. I want to move these files to another directory and at the same time renaming them with the directory name so that they are distinguished and are not over-written.

EDIT: All the directories are in the same directory. Destination is one directory on the system which could be anything. We read directory and read file form it and rename it exactly as the directory name and put it to the destination.

An important constraint is that the name of the file is given which will be in all of the directories. Directories might contain other files bit also the one which is given

Thanks a lot

share|improve this question
The question is a bit vague. You should clarify whether the directories are in the same directory or not, what exactly you want the destination filenames to be, etc... Examples would help. – geirha Apr 14 '12 at 22:53
@geirha I tried explaining... Please let me know if anything is still unclear. Thanks – Shan Apr 14 '12 at 23:02
up vote 1 down vote accepted

Assuming the filename of these files are thefilename, you've cded to the directory containing these directories, and you want to move them to /path/to/dest, the following shell loop should do the trick

for file in */thefilename; do
    echo mv -iv "./$file" "/path/to/dest/${file%/*}"

You can run that directly in an interactive shell, or put it in a file and run it as a script.

I added an echo to make it only print the mv commands. If the output looks correct, remove the echo and run it again to have it actually do the moving.

share|improve this answer

If you use bash, you can do the following:

$ for i in *WhatEverMatchesYourOriginalDirectories*
  cd $i
  for j in *
    mv $j ../Target/${i}-${j}
  cd ..

This will move every file in the directories matched by the first wildcard into the Target directory.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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