Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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
1  
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

2 Answers 2

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%/*}"
done

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*
do
  cd $i
  for j in *
  do
    mv $j ../Target/${i}-${j}
  done
  cd ..
done

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

share|improve this answer

Your Answer

 
discard

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.