简体   繁体   English

将子文件夹名称添加到文件名,并将文件移动到当前目录

[英]Prefixing sub-folder names to a filename, and moving file to current directory

I have a car stereo that reads USB sticks, but the stereo's "random" function only works on one folder, so I want to move all files to a parent folder, "STICK/music", but to have the Artist, and Album if any, added to the filename.我有一个读取 USB 棒的汽车音响,但立体声的“随机”function 仅适用于一个文件夹,所以我想将所有文件移动到父文件夹“棒/音乐”,但如果有艺术家和专辑任何,添加到文件名。 But what I've done is sort of hard-coded, and I'd like to be able to use different sticks.但是我所做的有点硬编码,我希望能够使用不同的棒。 I would like to have these ("RHYTHMBLUES" is the name of the stick):我想要这些(“RHYTHMBLUES”是棒的名称):

/media/homer/RHYTHMBLUES/music/Artist/Album/name1.mp3
/media/homer/RHYTHMBLUES/music/Artist/Album/name2.mp3
/media/homer/RHYTHMBLUES/music/Artist/name3.mp3
/media/homer/RHYTHMBLUES/music/Artist/name4.mp3

renamed with folder names and moved to "music":用文件夹名称重命名并移至“音乐”:

/media/homer/RHYTHMBLUES/music/Artist-Album-name1.mp3
/media/homer/RHYTHMBLUES/music/Artist-Album-name2.mp3
/media/homer/RHYTHMBLUES/music/Artist-name3.mp3
/media/homer/RHYTHMBLUES/music/Artist-name4.mp3

I thought of having a bash command to call "doit":我想有一个 bash 命令来调用“doit”:

find . -type d -exec sh -c "cd \"{}\" ; /home/homer/doit \"{}\" " \;

and "doit" would contain:和“doit”将包含:

#!/bin/sh -x
echo --------------------------------
pwd
for i in *.mp3
  do new=$(printf "${1}/${i}")
  # remove the ./ at the beginning of the name
  new=`echo "${new}" | cut -c 3-`
  # replace folder separators
  new=`echo "${new}" | tr '/' '-'`
  echo "$i" "/media/homer/RHYTHMBLUES/music/$new"
  mv -T "$i" "/media/homer/RHYTHMBLUES/music/$new"
done

doitbaby.sh doitbaby.sh

#!/bin/sh

moveTo () { # $1=directory, $2=path, $3=targetName
    local path="$(realpath "$1")"
    for file in "$path"/*; do
        if [ -d "$file" -a -n "$3" ]; then
            moveTo "$file" "$2" "$3""${file##*/}"-
        elif [ -d "$file" ]; then
            moveTo "$file" "$path" "${file##*/}"-
        elif [ -f "$file" -a "${file##*.}" = 'mp3' ]; then
            echo 'FROM: '"$file"
            echo 'TO  : '"$2"/"$3""${file##*/}"
            # mv "$file" "$2"/"$3""${file##*/}" # Uncomment this for real usage.
        fi
    done
}
removeEmptyDirs () {
    local path="$(realpath "$1")"
    for file in "$path"/*; do
        if [ -d "$file" ]; then
            rm -fR "$file"
        fi
    done
}
moveTo "$1"
# removeEmptyDirs "$1" # Uncomment this for real usage.

Note I have commented 2 lines in the above script.注意我在上面的脚本中注释了 2 行。 Test it first before any further real actions.在任何进一步的实际操作之前先对其进行测试。

Call the script like this: (Make sure the path is correct. This is the expected path by this script by the way.)像这样调用脚本:(确保路径正确。顺便说一下,这是该脚本的预期路径。)

./doitbaby.sh '/media/homer/RHYTHMBLUES/music/'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM