How to create folders with file names and then move files to folders?

I have hundreds of text files in a folder with a name using this kind of naming convention:

Bandname1 - song1.txt
Bandname1 - song2.txt
Bandname2 - song1.txt
Bandname2 - song2.txt
Bandname2 - song3.txt
Bandname3 - song1.txt
..etc.

I would like to create folders for different groups and move text files to these folders. How can I achieve this using bash, perl or python script?

+5
source share
7 answers

gregseth answer will work, just replace trimwith xargs. You can also eliminate the test ifsimply by using mkdir -p, for example:

for f in *.txt; do
    band=$(echo "$f" | cut -d'-' -f1 | xargs)
    mkdir -p "$band"
    mv "$f" "$band"
done

, trim xargs , xargs , .

+1

xargs:

for f in *.txt; do
    band=${f% - *}
    mkdir -p "$band"
    mv "$f" "$band"
done
+4

Perl

use File::Copy move;
while (my $file= <*.txt> ){
    my ($band,$others) = split /\s+-\s+/ ,$file ;
    mkdir $band;
    move($file, $band);
}
+2

, , EasyTAG. , , :

alt text
(: sourceforge.net)

: ", " [Artist] - [ ]/[ ] - [title] ". . - .

+1

:

for f in *.txt
do
  band=$(echo "$f" | cut -d'-' -f1 | trim)
  if [ -d "$band" ]
  then
    mkdir "$band"
  fi
  mv "$f" "$band"
done
0

This Python program assumes that the source files are in dataand that the new directory structure must be in target(and that it already exists).

The key point is that it os.path.walkwill navigate through the directory structure dataand call myVisitorfor each file.

import os
import os.path

sourceDir = "data"
targetDir = "target"

def myVisitor(arg, dirname, names):
    for file in names:
        bandDir = file.split("-")[0]
        newDir = os.path.join(targetDir, bandDir)
        if (not os.path.exists(newDir)):
            os.mkdir(newDir)

        newName = os.path.join(newDir, file)
        oldName = os.path.join(dirname, file)

        os.rename(oldName, newName)

os.path.walk(sourceDir, myVisitor, None)
0
source
ls |perl -lne'$f=$_; s/(.+?) - [^-]*\.txt/$1/; mkdir unless -d; rename $f, "$_/$f"'
-1
source

All Articles