我有成百上千个文本文件,它们都存储在一个以以下命名规则命名的文件夹中:
Bandname1 - song1.txt
Bandname1 - song2.txt
Bandname2 - song1.txt
Bandname2 - song2.txt
Bandname2 - song3.txt
Bandname3 - song1.txt
..etc.
我想为不同的乐队创建文件夹,并将相应的文本文件移动到这些文件夹中。我该如何使用bash、perl或python脚本实现这一目标?
我有成百上千个文本文件,它们都存储在一个以以下命名规则命名的文件夹中:
Bandname1 - song1.txt
Bandname1 - song2.txt
Bandname2 - song1.txt
Bandname2 - song2.txt
Bandname2 - song3.txt
Bandname3 - song1.txt
..etc.
不需要使用trim或xargs:
for f in *.txt; do
band=${f% - *}
mkdir -p "$band"
mv "$f" "$band"
done
use File::Copy move;
while (my $file= <*.txt> ){
my ($band,$others) = split /\s+-\s+/ ,$file ;
mkdir $band;
move($file, $band);
}
gregseth的答案是可行的,只需将trim
替换为xargs
即可。您还可以通过使用mkdir -p
来消除if
测试,例如:
for f in *.txt; do
band=$(echo "$f" | cut -d'-' -f1 | xargs)
mkdir -p "$band"
mv "$f" "$band"
done
严格来说,trim
或xargs
甚至都不是必要的,但xargs
至少可以去除任何额外的格式,所以也无妨。
你要求一个特定的脚本,但如果这是为了组织你的音乐,你可能想要查看EasyTAG。它有非常具体和强大的规则,可以根据你的喜好自定义组织你的音乐:
(来源:sourceforge.net)
这个规则说,“假设我的文件名结构为“[艺术家] - [专辑标题]/[曲目编号] - [标题]”。然后你可以标记它们,或者将文件移动到任何新的模式,或者做任何其他事情。
for f in *.txt
do
band=$(echo "$f" | cut -d'-' -f1 | trim)
if [ -d "$band" ]
then
mkdir "$band"
fi
mv "$f" "$band"
done
这个Python程序假设源文件在data
中,并且新的目录结构应该在target
中(并且它已经存在)。
关键点是os.path.walk
将遍历data
目录结构,并为每个文件调用myVisitor
。
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)
ls |perl -lne'$f=$_; s/(.+?) - [^-]*\.txt/$1/; mkdir unless -d; rename $f, "$_/$f"'