【问题标题】:Prefixing sub-folder names to a filename, and moving file to current directory将子文件夹名称作为文件名的前缀,并将文件移动到当前目录
【发布时间】:2021-05-09 07:28:52
【问题描述】:

我有一个可以读取 USB 记忆棒的汽车音响,但音响的“随机”功能仅适用于一个文件夹,所以我想将所有文件移动到父文件夹“STICK/music”,但要让艺术家,和专辑(如果有)添加到文件名中。 但是我所做的有点硬编码,我希望能够使用不同的棒。 我想要这些(“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

用文件夹名称重命名并移至“音乐”:

/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

我想有一个 bash 命令来调用“doit”:

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

并且“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

【问题讨论】:

  • 您打算在哪个目录下发出 bash 命令
  • 可能在 /media/homer/STICKNAME/music/,但愿意听取建议 :)

标签: linux shell


【解决方案1】:

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.

注意 我在上面的脚本中注释了 2 行。在任何进一步的实际操作之前先对其进行测试。

这样调用脚本:(确保路径正确。顺便说一下,这是该脚本的预期路径。)

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

【讨论】:

  • 谢谢。将测试这个 arvo。
  • 哇,谢谢达克曼。我没想过使用递归:做得好。像梦一样工作。
  • 最后一点,我用了很久的删除空目录功能是:find . -type d -empty -print -delete
  • @Alfredo 对你有好处。你的肯定比我的更好,更安全。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
  • 2016-05-07
  • 2022-11-16
  • 1970-01-01
  • 2016-01-17
  • 1970-01-01
  • 2020-11-10
相关资源
最近更新 更多