【问题标题】:Script to automate moving files from multiple directories to newly created directories with the same suffix (not file extension)用于自动将文件从多个目录移动到具有相同后缀(不是文件扩展名)的新创建目录的脚本
【发布时间】:2019-07-14 14:47:09
【问题描述】:

我正在为存档处理大量原生数字材料,但我不得不手动创建目录并从多个目录中查找文件并将其移动到新创建的目录中,这让我的速度变慢了。

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

-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 结尾 粗体=库存编号

【问题讨论】:

  • 能否请您发布每个文件夹的文件名示例?这将有助于澄清您的需求。
  • 刚刚更新的帖子。
  • 请您发布一个最小的可行示例以及您遇到的问题?
  • 我没有例子。但我会很高兴被指出正确的方向。
  • 给我 5 分钟,我会发布一些东西,我正在刷新我的 bash :-)

标签: bash


【解决方案1】:

这是一个程序序列,用于遍历您的 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

【讨论】:

【解决方案2】:

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

测试用例:

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)'

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

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

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/ 子文件夹中。

【讨论】:

    猜你喜欢
    • 2014-06-18
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多