脚本自动将文件从多个目录移动到具有相同后缀(不是文件扩展名)的新创建目录

时间:2019-02-20 20:00:28

标签: bash

我正在处理大量原始数字资料,用于存档,但是我不得不手动创建目录并将文件从多个目录中查找并移动到新创建的目录中,这让我感到很慢。

问题:我有三个目录,其中包含来自不同来源的三种不同类型的内容:

-disk_images -evidence_photos -document_scans

磁盘映像是由案例附带的CD创建的,并写出了一些案例,这些案例对于后代来说是可以访问和保存的,因此已对其进行了拍摄,并带有前缀和库存编号加载到证据照片文件夹中。一些CD在纸上带有索引,并且已经过扫描和OCR扫描,并带有前缀和库存编号的文档已加载到文档扫描文件夹中。并非所有磁盘映像都有相应的照片或扫描图像,因此这些文件夹中的库存编号不是线性的。

我一直在尝试编写一种方法来编写脚本,该脚本将浏览每个目录并将具有相同后缀(而不是扩展名)的文件移动到每个库存编号的新创建目录,但是他的方法超出了我的专业知识。任何帮助将不胜感激,我将非常乐于澄清是否需要。

文件名示例: -disk_images / ahacd_ 001 .iso
-evidence_photos / ahacd_case_ 001 .jpg -document_scans / ahacd_notes_ 001 .pdf

可能的新目录名称= ahacd_001

所有库存编号为001的文件都需要以ahacd_001结尾 粗体=库存编号

2 个答案:

答案 0 :(得分:0)

这是一个程序清单,用于遍历您的3个起始文件夹并拆分文件名:

for folder in `ls -d */` #list directories 
do 
  echo "moving folder $folder"
  ls $folder | while read file # list the files in the directory
  do
    echo $file
    # split the file name with awk and get the first part ( 'ahacd' ) and the last ('002')
    echo $file | awk -F '.' '{print $1}' |awk -F '_' '{print $1 "_" $NF}' 

    # when you are statisfied that your file splitting works...
    mkdir folder # create your folder
    move file # move the file
  done
done

一些分割文件名的指针: Get last field using awk substr

答案 1 :(得分:0)

首先,我想说一个以-开头的文件或目录名称是一个坏主意,即使允许使用。

测试用例:

mkdir -p /tmp/test/{-disk_images,-evidence_photos,-document_scans}
cd /tmp/test
touch -- "-disk_images/ahacd_001.iso"       #create your three test files
touch -- "-evidence_photos/ahacd_case_001.jpg"
touch -- "-document_scans/ahacd_notes_001.pdf"
find -type f|perl -nlE \
'm{.*/(.*?)_(.*_)?(\d+)\.}&&say qq(mkdir -p target/$1_$3; mv "$_" target/$1_$3)'

...不会移动文件,只会向您显示它认为应该运行的命令。

如果您要运行这些命令,请通过在同一|bash命令的末尾添加find|perl来运行它们:

find -type f|perl -nlE \
'm{.*/(.*?)_(.*_)?(\d+)\.}&&say qq(mkdir -p target/$1_$3; mv "$_" target/$1_$3)' \
| bash

find -ls   #to see the result

这三个文件现在都位于target/ahacd_001/子文件夹中。