循环浏览文件夹并使用文件夹名称依次重命名每个文件夹中的所有文件

时间:2014-06-03 05:12:33

标签: macos for-loop terminal renaming

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

结构看起来像

/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工作流程并使用变量,但很难将文件夹名称指定为变量并使循环起作用。

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

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

这应该很适合你。将它作为“RenameImages”保存在HOME目录中,然后将其设置为可执行文件:

cd
chmod +x RenameImages

然后你可以在每个目录(-exec)上运行它(-type d),如下所示:

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并再次运行。

答案 1 :(得分:0)

我想提出另一种方法,因为你提到你尝试过使用Automator。此文件搜索和处理软件:http://www.softpedia.com/get/File-managers/JFileProcessor.shtml https://github.com/stant/jfileprocessor

将允许您使用glob或正则表达式搜索文件,在子文件夹中搜索X或所有深度,按名称,大小,日期。您可以保存到列表窗口或文件。然后你可以运行一个groovy(想想java)脚本来做任何你想要的文件列表; zip或tar它们,修改列表字符串,如sed,delete,move,copy files,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");
        }

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