Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create folders using file names and then move files into folders?

I have hundreds of text files in a folder named 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 bands and move according text files into these folders. How could I achieve this using bash, perl or python script?

like image 414
jrara Avatar asked Jan 31 '10 16:01

jrara


4 Answers

It's not necessary to use trim or xargs:

for f in *.txt; do
    band=${f% - *}
    mkdir -p "$band"
    mv "$f" "$band"
done
like image 110
Dennis Williamson Avatar answered Nov 14 '22 11:11

Dennis Williamson


with Perl

use File::Copy move;
while (my $file= <*.txt> ){
    my ($band,$others) = split /\s+-\s+/ ,$file ;
    mkdir $band;
    move($file, $band);
}
like image 34
ghostdog74 Avatar answered Nov 14 '22 13:11

ghostdog74


gregseth's answer will work, just replace trim with xargs. You could also eliminate the if test by just using mkdir -p, for example:

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

Strictly speaking the trim or xargs shouldn't even be necessary, but xargs will at least remove any extra formatting, so it doesn't hurt.

like image 1
bjlaub Avatar answered Nov 14 '22 11:11

bjlaub


You asked for a specific script, but if this is for organizing your music, you might want to check out EasyTAG. It has extremely specific and powerful rules that you can customize to organize your music however you want:

alt text
(source: sourceforge.net)

This rule says, "assume my file names are in the structure "[artist] - [album title]/[track number] - [title]". Then you can tag them as such, or move the files around to any new pattern, or do pretty much anything else.

like image 1
John Feminella Avatar answered Nov 14 '22 12:11

John Feminella