regex - 如何移动多个不同目录中的多个文件(在 Linux 上)

标签 regex linux file bash shell

我的问题是我在单个目录中有太多文件。我不能“ls”这个目录,因为它太大了。我需要将所有文件移动到更好的目录结构中。

我以相反的方式使用 ID 的最后 3 位数字作为文件夹。

例如 ID 2018972 将进入 /2/7/9/img_2018972.jpg

我已经创建了目录,但现在我需要有关 bash 脚本的帮助。我知道 ID,范围是 1,300,000 - 2,000,000。但我无法处理正则表达式。

我不想像这样移动所有文件:

/images/folder/img_2018972.jpg -> /images/2/7/9/img_2018972.jpg

对于此主题的任何帮助,我将不胜感激。谢谢!

最佳答案

编辑:在评论中进行解释后,存在以下假设:

  • 文件名格式为img_<id>.jpgimg_<id>_<size>.jpg
  • 新目录是id的最后三位数字的倒序

使用 Bash:

for file in /images/folder/*.jpg; do 
    fname="${file%.*}"      # remove extension and _<size>
    [[ "$fname" =~ img_[0-9]+_[0-9]+$ ]] && fname="${fname%_*}"

    last0="${fname: -1:1}"  # last letter/digit
    last1="${fname: -2:1}"  # last but one letter/digit
    last2="${fname: -3:1}"  # last but two letter/digit

    newdir="/images/$last0/$last1/$last2"
    # optionally check if the new dir exists, if not create it
    [[ -d "$newdir" ]] || mkdir -p "$newdir"

    mv "$file" "$newdir"
done

如果*无法处理它(尽管我认为 for 循环中的 * 没有限制),
使用 find正如@Michał Kosmulski 在评论中所建议的那样

while read -r; do 
    fname="${REPLY%.*}"     # remove extension and _<size>
    [[ "$fname" =~ img_[0-9]+_[0-9]+$ ]] && fname="${fname%_*}"

    last0="${fname: -1:1}"  # last letter/digit
    last1="${fname: -2:1}"  # last but one letter/digit
    last2="${fname: -3:1}"  # last but two letter/digit

    newdir="/images/$last0/$last1/$last2"
    # optionally check if the new dir exists, if not create it
    [[ -d "$newdir" ]] || mkdir -p "$newdir"

    mv "$REPLY" "$newdir"
done < <(find /images/folder/ -maxdepth 1 -type f -name "*.jpg")

关于regex - 如何移动多个不同目录中的多个文件(在 Linux 上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10172225/

相关文章:

linux - 使用 qt 最小化应用程序

c++ - Qt读取文本文件的一些信息

objective-c - 将日志附加到文件中

Python - 用空格连接字符串的字符

php - 如果正则表达式后面跟着空格和关键字,则跳过匹配

linux - 如何让我的 init.d 脚本改变用户

python - C++ boost + Python : undefined reference to Py_Dealloc

Python:如何在使用正则表达式时跳过有多余字符的行?

javascript - 将变量插入正则表达式

c# - 如何从内存流中打开文件