如何使用文件名创建文件夹,并将文件移动到文件夹中?

5

我有成百上千个文本文件,它们都存储在一个以以下命名规则命名的文件夹中:

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

我想为不同的乐队创建文件夹,并将相应的文本文件移动到这些文件夹中。我该如何使用bash、perl或python脚本实现这一目标?

4
你会考虑自己编写一个脚本并在这里发布吗?我认为如果人们对此进行评论,而不是为你编写脚本,那将更具有指导意义。 - Noufal Ibrahim
7个回答

4

不需要使用trim或xargs:


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

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

1

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

严格来说,trimxargs甚至都不是必要的,但xargs至少可以去除任何额外的格式,所以也无妨。


1

你要求一个特定的脚本,但如果这是为了组织你的音乐,你可能想要查看EasyTAG。它有非常具体和强大的规则,可以根据你的喜好自定义组织你的音乐:

alt text
(来源:sourceforge.net)

这个规则说,“假设我的文件名结构为“[艺术家] - [专辑标题]/[曲目编号] - [标题]”。然后你可以标记它们,或者将文件移动到任何新的模式,或者做任何其他事情。


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

谢谢,但是我的Bash(我在Mac 10.6.2上)显示: -bash:trim:命令未找到 我尝试了textutil :: text,但我得到了同样的答案。 - jrara

0

这个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)

-1
ls |perl -lne'$f=$_; s/(.+?) - [^-]*\.txt/$1/; mkdir unless -d; rename $f, "$_/$f"'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接