1

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).

  • 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
0

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.

  • Thank you very much! Works perfectly: exactly what I wanted. – paddymelon Jul 1 '13 at 2:52
1

Another Solution :

#!/usr/bin/env bash

Dir="/tmp/directory/"

for f in "$Dir"/*;
do
    SubDir="${f%.*}"
    mkdir -- "$SubDir"
    mv -- "${f}" "$SubDir/"
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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