Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

The use of a renaming program severely screwed up some of my files. I'm trying to get them back in order.

I have file structure like this:

./Hello World/some-filename.ext
./Kitty Parade/another.ext
./Third Example/abc.ext
./some-filename.ext2
./another.ext2
./abc.ext2

The goal is the move the files in current folder (./) back to their original folders.

For example:
another.ext2 belongs in the ./Kitty Parade/ folder
some-filename.ext2 belongs in the ./Hello World/ folder
abc.ex2 belongs in the ./Third Example/ folder`

The rule can be described as this: If a file exists in current folder (./), find a folder than contains a file with the same filename (but with different extension) and move it to that folder. Note: there is no reliable relation between ./myFilename and that file's ./originalFolderName.

This happened to over 4,000 files otherwise I'd do it manually. Any possible help?

share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

Try this piece of shell magic:

for i in *.*; do
  BASE=$(basename "$i" .ext2)
  LIST=*/"${BASE}".*
  DIR=$(dirname "${LIST}")
  mv -n "$i" "${DIR}"
done

Or as an oneliner:

for i in *.*; do mv -n "$i" "$(dirname */"$(basename "$i" .ext2)".*)"; done

Before:

whitequark@forth:~/test$ ls *
test 1.ext2  test 2.ext2  test 3.ext2

f 1:
test 1.ext

f 2:
test 2.ext  test 3.ext

After:

whitequark@forth:~/test$ ls *
f 1:
test 1.ext  test 1.ext2

f 2:
test 2.ext  test 2.ext2  test 3.ext  test 3.ext2

The -n switch will protect you from overwriting anything.

share|improve this answer
    
ls */"${BASE}".* heh, nice Always used find for this. –  skarface Feb 1 '10 at 4:54
    
This is remarkable; thank you! –  macek Feb 1 '10 at 5:18
    
ls is not necessary: LIST=*/"${BASE}".* and `"$(dirname "/"$(basename "$i" .ext2)".")" –  Dennis Williamson Feb 1 '10 at 6:10
    
@Dennis: thanks, changed. that has remained from previous version of command. –  whitequark Feb 1 '10 at 6:26
add comment

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.