Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

bash - How do I extract a file name into 2 parts, making one into directory and the other one inside of it?

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

Sample Output

'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'

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

  • 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.

Note that you can install on macOS with homebrew:

brew install rename

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...