我如何将文件名提取为两部分,一部分进入目录,另一部分进入目录? [英] How do I extract a file name into 2 parts, making one into directory and the other one inside of it?

查看:117
本文介绍了我如何将文件名提取为两部分,一部分进入目录,另一部分进入目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按艺术家和姓名对所有mp3文件进行排序.目前,他们使用1个巨型文件名. 例如:歌手-歌曲名称.mp3 我想将其转换为 歌手/歌曲名称.mp3

I'm trying to sort all mp3 files by artist and name. At the moment, they're in 1 giant file name. E.g Artist - Song name.mp3 I want to convert this to Artist/Song name.mp3

这是到目前为止我尝试过的.在这种情况下,我使用了一个名为"hi \-\ hey"的测试文件:

Here's what I've tried so far. In this case, I was using a test file named "hi\ -\ hey":

#!/bin/bash
# filters by all .mp3 extensions in the current working directory 
for f in *.mp3; do
# extract artist and song name and remove spaces
        artist=${f%  -*}
        song=${f#*-  }
#make directory with the extracted artist name and move + rename the file into the directory
        mkdir -p $artist
        mv $f $artist/$song;
done

由于某种原因,它会创建一个带有歌曲名称的目录,而不是艺术家,并增加了很多错误:

For some reason, it's creating a directory with the song name instead of the artist in addition to a load of errors:

mv: cannot move 'hey.mp3' to a subdirectory of itself, 'hey.mp3/hey.mp3'
mv: cannot stat 'hi': No such file or directory
mv: cannot stat '-': No such file or directory
mv: 'hey.mp3/hi' and 'hey.mp3/hi' are the same file
mv: cannot stat '-': No such file or directory

推荐答案

到目前为止,最简单的方法是使用rename a.k.a. Perl rename.

By far the simplest way of doing this is to use rename a.k.a. Perl rename.

基本上,您想用正斜杠目录分隔符替换序列SPACE-DASH-SPACE,因此命令为:

Basically, you want to replace the sequence SPACE-DASH-SPACE with a forward slash directory separator, so the command is:

rename --dry-run -p 's| - |/|' *mp3

示例输出

'Artist - Song name.mp3' would be renamed to 'Artist/Song name.mp3'
'Artist B - Song name 2.mp3' would be renamed to 'Artist B/Song name 2.mp3'

如果看起来正确,只需删除--dry-run并再次运行即可.使用rename的好处是:

If that looks correct, just remove --dry-run and run it again for real. The benefits of using rename are:

  • 可以在进行真实测试之前先进行试运行
  • 它将使用-p选项创建所有必要的目录
  • 它不会在没有警告的情况下破坏(覆盖)文件
  • 您将拥有Perl的全部功能,并且可以根据需要使重命名更加复杂.
  • it can do a dry-run to test before you run for real
  • it will create all necessary directories with the -p option
  • it will not clobber (overwrite) files without warning
  • you have the full power of Perl available to you and can make your renaming as sophisticated as you wish.

请注意,您可以使用自制软件 macOS 上安装:

Note that you can install on macOS with homebrew:

brew install rename

这篇关于我如何将文件名提取为两部分,一部分进入目录,另一部分进入目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆