gpt4 book ai didi

linux - 在 Bash 中,根据文件名将文件移动到目录

转载 作者:太空宇宙 更新时间:2023-11-04 05:49:49 25 4
gpt4 key购买 nike

我有很多文件,其名称具有以下格式:GroupName - SongName-id.mp3 其中 id 的长度为 11 个字符。我想将它们移动到诸如文件 GroupName - SongName-id.mp3 将被重命名为 GroupName/SongName.mp3 的目录中我在网上做了一些研究(如 this ),但我不知道如何使用 grep 检索 GroupNameSongName 。编辑:GroupName 目录可以已经存在,也可以不存在,这取决于。

我首先尝试使用以下脚本:

#!/bin/bash
for filename in *.mp3;do
group=$(echo $filename | grep -oE ".* - .*-.{11}\.mp3")
# I don't know what regex should I place above

# do all the other stuff here ...
done

最佳答案

考虑以下复杂的解决方案:

#!/bin/bash

find . -regextype sed -regex '[^-]* - [^-]*-.\{11\}\.mp3' -print0 | while read -r -d $'\0' file
do
IFS=\; read -a parts <<< $(sed -E 's:.+/(\S[^/-]+\S) - (\S+)-\S{11}(\.mp3):\1;\2\3:' <<< "$file")
mkdir -p "${parts[0]}"
mv "$file" "${parts[0]}/${parts[1]}"
done
<小时/>

详细信息:

  • -regextype sed(在find命令中)-设置正则表达式的类型

  • -regex(在find命令中)-用于通过正则表达式模式查找文件的选项

  • -print0$'\0' - 确保用零(空)字符分隔文件名

  • read -a parts - 读取 sed 结果(返回由 ; 分隔的组名文件名)到数组

  • mkdir -p "${parts[0]}" - 创建名称为groupname的目录(如果不存在)

关于linux - 在 Bash 中,根据文件名将文件移动到目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44474534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com