Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This might sound like something quite odd but for my HTPC, I need to rearrange how my files are stored such that each of the individual files in a folder needs to be moved to a subdirectory of its own (with the same name as the file).

I.E. - Currently the directory is:

directory/
- a.file
- b.file
- c.file

and I want to change it to:

directory/
- a/
-- a.file
- b/
-- b.file
- c/
-- c.file

I don't think this is terribly tricky but it's just odd and I haven't found anybody doing it before: I think it can be done with find and exec but I'm a bit of a battler and can't quite get it.

Thank you very much in advance (or even just for taking the time to read this).

share|improve this question
    
Always the same extension? –  Hauke Laging Jul 1 '13 at 2:19
    
No, but all the files in the folder I want this done too. Also, there's only 3 or so file extensions so if you know a way of doing it for the same extension, I could just run the command thrice, changing the extension each time: it's not a huge concern. –  paddymelon Jul 1 '13 at 2:22

2 Answers 2

up vote 0 down vote accepted

Write a shell script which gets the files as parameters:

#!/bin/bash

for filepath; do
  parentpath="${filepath%/*}"
  if [ "$parentpath" != "$filepath" ]; then # $file contains a /
    file="${filepath#"$parentpath"/}"
  else
    file="$filepath"
    parentpath=""
  fi
  filename="${file%.*}"
  if [ -z "$parentpath" ]; then
    mkdir -p "$filename" && mv "$file" "$filename"
  else
    mkdir -p "${parentpath}/$filename" &&
      mv "$filepath" "${parentpath}/$filename"
  fi
done

You can call this script as ./script *.ext1 *.ext2 *.ext3 for not too huge numbers of files or as find ... -exec ./script {} + for huge numbers.

share|improve this answer
    
Thank you very much! Works perfectly: exactly what I wanted. –  paddymelon Jul 1 '13 at 2:52

Another Solution :

#!/usr/bin/env bash

Dir="/tmp/directory/"

for f in "$Dir"/*;
do
    SubDir="${f%.*}"
    mkdir -- "$SubDir"
    mv -- "${f}" "$SubDir/"
done
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.