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?
It's not necessary to use trim or xargs:
for f in *.txt; do
band=${f% - *}
mkdir -p "$band"
mv "$f" "$band"
done
with Perl
use File::Copy move;
while (my $file= <*.txt> ){
my ($band,$others) = split /\s+-\s+/ ,$file ;
mkdir $band;
move($file, $band);
}
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.
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:
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With