I'm currently trying to organize several thousand files which are named according to what's in them, and the various "tags," if you will, are separated by spaces. So, for example:

foo_bar bar_foo.txt

I'm relatively new to Linux/Unix, and was wondering if there was a way to iterate through every file, create folders based on the tags, and copy the files to those folders?

So we'd end up with:

./foo_bar bar_foo.txt
./foo_bar/foo_bar bar_foo.txt
./bar_foo/foo_bar bar_foo.txt

So far, I've been manually doing everything like this:

mkdir foo_bar
cp *foo_bar* foo_bar/
mkdir bar_foo
cp *bar_foo* bar_foo/

Obviously this is pretty time-inefficient, so I'm just looking for a way to automatically do it.

Edit: Some more examples:


./a b c d.txt
./b a d.txt
./c d e.txt
./d a.txt


All original files still in parent directory, plus:

./a/a b c d.txt
./a/b a d.txt
./a/d a.txt

./b/a b c d.txt
./b/b a d.txt

./c/a b c d.txt
./c/c d e.txt

./d/a b c d.txt
./d/b a d.txt
./d/c d e.txt
./d/d a.txt

./e/c d e.txt

1 Answer 1


try this.. remove the echo.. if you are happy with the commands...

ls * | awk '{print $1}' | sort -u | while read a; do echo mkdir -p $a; echo mv ${a}*txt ${a}; done

modified answer

$ ls
    a b c d.txt  b a d.txt  c d e.txt  d a.txt
$ ls * | sed "s/.txt//;s/ /\n/g" | sort -u | while read file; do echo mkdir -p $file; echo mv *${file}*.txt ${file}; done
    mkdir -p a
    mv a b c d.txt b a d.txt d a.txt a
    mkdir -p b
    mv a b c d.txt b a d.txt b
    mkdir -p c
    mv a b c d.txt c d e.txt c
    mkdir -p d
    mv a b c d.txt b a d.txt c d e.txt d a.txt d
    mkdir -p e
    mv c d e.txt e

Note: as you want the file be present in your original directory.. use cp instead of mv

  • Well, that almost works, but it only sorts by the first tag, so if we had multiple files with the foo_bar tag, but it wasn't the first tag, they wouldn't end up in the same folder.
    – Swammy
    Dec 9, 2016 at 9:55
  • can you add more input and expected output... more files and which folder it has to go...etc...
    – Kamaraj
    Dec 9, 2016 at 9:57
  • Alright, I added a few more.
    – Swammy
    Dec 9, 2016 at 10:03
  • check the modified answer
    – Kamaraj
    Dec 9, 2016 at 10:11
  • If I just remove the various ".txt"s from your answer, will that make it work with every file type, or would it require further modification? I just used .txt in the examples because it's the most common of all the files we have, but there are some of other types.
    – Swammy
    Dec 9, 2016 at 10:16

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.