Reputation: 41
Solution:
#!/bin/bash
for f in *.mp3; do
d="${f% - *}"
if [ -d $d ]; then
mv "$f" "$d/";
else
mkdir "$d" && mv "$f" "$d/";
fi
done
I'm trying this:
$ echo "foo - bar.ext" | sed 's/\('" - "'\).*/\1/' | sed 's/ - //'
which gives me just "foo". I guess there is a better way...Don't hit me hard, I'm new to sed. But now, how to include it in a loop like this:
#!/bin/bash
for f in *.ext; do
d="${f%.*}"
#Extract Filename String before the " - " and write back to $d
mkdir "$d" && mv "$f" "$d/";
done
Thanks in advance
Further information:
$f shall remain unchanged while a directory name, stored in $d, shall contain only the "foo"- part of a pattern matching "foo - bar.ext".
Basically, a list of files, following the pattern "foo - bar.ext" should be moved to directories which are named "foo".
E.g.: foo1 - bar1.ext foo1 - bar2.ext foo1 - bar2.ext --> will be moved to subdir "foo1"
anotherfoo - anotherbar.ext --> will be moved to subdir "anotherfoo"
Upvotes: 2
Views: 437
Reputation: 50124
You have it almost already. Only a three characters are missing in your code fragment.
#!/bin/bash
for f in *.ext; do
d="${f% - *}"
mkdir "$d" && mv "$f" "$d/";
done
Upvotes: 1