【问题标题】:Looping through folders and renaming all files in each folder sequentially with folder name遍历文件夹并使用文件夹名称顺序重命名每个文件夹中的所有文件
【发布时间】:2014-06-03 05:12:33
【问题描述】:

我有一系列子文件夹,每个子文件夹上都有图片。

结构看起来像

/stuff/
   IMG_012.JPG
   IMG_013.JPG
   IMG_014.JPG

/morestuff/
   IMG_022.JPG
   IMG_023.JPG
   IMG_024.JPG

我想在我的 mac 终端上编写一个脚本来循环遍历每个文件夹并按顺序重命名图像,包括文件夹名称。所以,上面的结构看起来像:

/stuff/
   stuff_1.JPG
   stuff_2.JPG
   stuff_3.JPG

/morestuff/
   morestuff_1.JPG
   morestuff_1.JPG
   morestuff_1.JPG

我最初尝试创建 Automator 工作流程并使用变量,但难以将文件夹名称分配为变量并使循环正常工作。

我希望终端有一个优雅的解决方案。

有什么想法吗?

【问题讨论】:

标签: macos for-loop terminal renaming


【解决方案1】:

这应该很适合您。将它作为“RenameImages”保存在您的 HOME 目录中,然后使其可执行,如下所示:

cd
chmod +x RenameImages

然后你可以像这样在每个目录(-type d)上运行它(-exec):

find . -type d -exec ./RenameImages {} \;

这是脚本:

#!/bin/bash
# Ignore case, i.e. process *.JPG and *.jpg
shopt -s nocaseglob
shopt -s nullglob

# Go to where the user says
echo Processing directory $1
cd "$1" || exit 1

# Get last part of directory name
here=$(pwd)
dir=${here/*\//}
i=1
for image in *.JPG 
do
   echo mv "$image" "${dir}${i}.jpg"
   ((i++))
done

目前它什么也不做,只是告诉你它会做什么。如果您喜欢它的功能,只需从第 3 行到最后一行删除单词 echo,然后再次运行。

【讨论】:

    【解决方案2】:

    我只是想抛出另一种方法来做到这一点,因为你提到你尝试使用 Automator。本文件搜索处理软件:http://www.softpedia.com/get/File-managers/JFileProcessor.shtmlhttps://github.com/stant/jfileprocessor

    将允许您按名称、大小、日期在 X 或所有深度的子文件夹中搜索带有 glob 或正则表达式的文件。您可以保存到列表窗口或文件。然后你可以运行一个groovy(想想java)脚本来对文件列表做任何你想做的事情; zip 或 tar,修改列表字符串,如 sed、删除、移动、复制文件、grep 或 ls -l 它们,等等。在您的情况下,您可以修改现有的 groovy 示例以执行以下操作:

        int numItems = defaultComboBoxModel.getSize();
        System.out.println( "defaultComboBoxModel.getSize() num of items =" + numItems + "=" );
        String str = "";
        for( int i = 0; i < numItems; i++ )
            {
            str = defaultComboBoxModel.getElementAt( i ).toString();
            System.out.println( "file of index =" + i + "   str =" + str + "=" );
    
                String cmd = "mv " + str + " " + i + ".jpg";  // or whatever
                def list = cmd.execute().text   // this stuff just captures output and write to a log file
                list.eachLine{
                    outFile << it;
                    }
                outFile << System.getProperty("line.separator") + "-------------------------------------" + System.getProperty("line.separator");
            }
    

    它还可以让您按摩您的列表,例如添加、删除、从另一个列表中减去一个列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      • 2021-11-06
      • 2016-12-18
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      • 2017-01-01
      相关资源
      最近更新 更多